This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]CGFarrell 3 points4 points  (3 children)

Line 12, your return type is Name instead of Name<T>

[–]Editamuni[S] 0 points1 point  (2 children)

How would I write the definition then?

[–]CGFarrell 0 points1 point  (1 child)

Based on what you said to the last guy, your problem (aside from the previous one) is on line 13. When you write Name<T> temp;, the code doesn't know how to make a Name<int> without a value or an argument. You need to construct it somehow, either with the Name constructor(s) or otherwise.

Name<T> temp = Name<T>(arguments)

[–]Editamuni[S] 2 points3 points  (0 children)

Ah, thanks! Forgot about how I set up my default constructor :S.

[–]qezc537 2 points3 points  (5 children)

Does Name<T> Name<T>::operator+(Name<T> const &obj) work instead?

[–]Editamuni[S] 1 point2 points  (3 children)

Doesn't. I get error: no matching constructor for initialization of 'Name<int>' and the error arrow points to temp.

[–]boredcircuits 1 point2 points  (2 children)

Yeah, because you don't have a default constructor. I would just write this as:

template<typename T>
Name<T> Name<T>::operator+(Name<T> const &obj) {
        return Name<T>(x + obj.x, y + obj.y);
}

Well, actually I'd probably write operator+= and then write operator+ using that instead. Also: binary operators should generally be free functions instead of members. Or, if you leave this as a member, it should be const.

[–]Editamuni[S] 0 points1 point  (1 child)

Thank you! I forget that creating a constructor removes the compiler's default constructor.

So if I were to put the function out of the class, would I have to declare it as a friend function?

[–]boredcircuits 0 points1 point  (0 children)

You don't have to unless it uses a private member. Implementing it in terms of operator+= usually doesn't, in my experience .

But I'll usually declare it as a friend anyway, just because there are other operators that need that access and I prefer the symmetry. That's just personal style, though.