+ 3
Declaration and assignment without calling parametised constructor
I've been trying overload some operators and I've run into corner. What I'm trying to do is, after I got my Object from sum, assign it to a newly declared variable, just like I would do it with integers (int c = a + b; a and b are int). I was expecting that either copy constructor or overloaded assignment would do the job, but it seems like it isn't the case. What would be a more elegant solution to this, e.g. not making another full constructor just for argument by value?
3 Answers
+ 2
The code fails to compile because operator+ returns an temporary object and the copy constructor takes it by reference.
But you cannot reference a temporary object so there is no constructor that c can choose to construct from.
What you can do is take it by const reference.
Or just leave out the copy constructor entirely and you get the default copy constructor which also works in this case.
Object c = a+b; or Object c(a+b); calls the copy constructor
c = a+b; call the copy assignment operator
Some more improvements you can make include changing the operator+ and operator= to take the object as const reference to prevent unnecessary copying.
operator= should return the object by reference.
so
void operator =(Object b)
{
this->x=b.x;
}
becomes
Object& operator=( const Object& o )
{
this->x += o.x;
return *this;
}
+ 3
https://code.sololearn.com/c717vQs09mLq/?ref=app
Posting this in comment because it didn't even fit in first post.
+ 1
Ok, thank you for your help. The issue was that compiler simply doesn't allow you to pass temporary object as non-constant reference because you might change object that's about to be deleted, which makes sense as a good practice but is a bit confusing as to why it doesn't even compile. Const reference made it work properly.
I also applied your other advice. I never thought to use const reference instead of pass by copy when I don't want their values to be changed. Also, I thought assignment operator doesn't return anything, but now I remember that it can, e.g. when you assign and pass as argument.