O3 = O1 + O2
This code has two operators: + and =. You seem to be trying to combine them into one.
First you'll want the + operator, which will take 2 const objects as input, and return a new object as its output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class Foo
{
int v;
public:
Foo operator + (const Foo& right) const
{
Foo sum; // <- our output
sum.v = this->v + right.v; // <- sum of the two objects being added: 'this' and 'right'
sum.v = v + right.v; // <- alternative way to do the same thing ('this' is optional)
return sum; // <- return the sum
}
};
|
So as you can see, the + operator takes 2 const objects as input (the left and right side of the operator), and returns a new object which contains their sum.
In the
O3 = O1 + O2;
example, O1 would become 'this', and O2 would become 'right'. Both should be constant because you would not expect that expression to modify O1 or O2.
After the + operator resolves, you are conceptually left with this:
1 2
|
O3 = O1 + O2; // <- start with this
O3 = sum; // <- becomes this... 'O1 + O2' operator overload called, returned 'sum' object
|
This is where the = operator takes over. Now we have a left side (O3) which is
NON-const (because we are modifying it), and a right side (sum) which [b]IS[b] const (because it is not being modified)
1 2 3 4 5 6 7
|
Foo& operator = (const Foo& right) // <- function is not const because we don't want 'this' to be const
{
// same idea here, 'this' is the left side of the '=' and 'right' is the right side.
v = right.v; // <- do the assignment to modify 'this'
return *this;
}
|
A few things to note about the = operator:
1) The weird return type of 'Foo&'.. and 'return *this;' is a reference trick to allow assignment chainging:
|
O3 = O2 = O1; // <- legal with above code
|
2) You generally do not need to overload the = operator, as the compiler will provide one for you. You only need to overload your own if your class has pointers for members or does any kind of memory management (which you generally should avoid by using smart pointers or container classes).