I understand, or at least have an Idea of, why the following code does not work:
class Spambar {
public:
Spambar() {};
Spambar(Spambar& sb) {};
Spambar operator + (Spambar sb) {
Spambar new_sb;
return new_sb;
}
};
int main() {
Spambar sb1;
Spambar sb2;
Spambar sb3 = sb1 + sb2; // <<< Error: "No matching function for call to ... "
}
I guess, the problem is that the copy-constructor expects a reference to a Spambar instance. As no reference but a shallow instance is returned, the compilation fails.
So, how do I get that to work?
The problem is that the result of
sb1 + sb2is a temporary; the copy constructor used to initialisesb3requires a non-constreference; and you can’t take a non-constreference to a temporary.You almost certainly want to fix this by changing the constructor’s parameter type to
Spambar const &. While you’re at it, you should almost certainly do the same tooperator+, and also make the operator itselfconst:If you’re doing something very strange, and actually want the copy-constructor to modify its argument, then you’ll have to either avoid passing temporaries to it, or do some nasty hackery with
mutableorconst_cast. In C++11, you would use a move constructor, with parameter typeSpambar &&, for this sort of thing.