I have overloaded the + operator like this
class sample
{
private :
int x;
public :
sample(int x1 =0)
{
x = x1;
}
sample operator+(sample s);
};
sample sample::operator+(sample s)
{
x = x + s.x;
return *this;
}
int main()
{
sample s1(10);
sample s2;
s2 = s2 + s1;
return 0;
}
Is this correct?
My question is If I want to add two different sample objects how will I overloaded the opeartor; e.g for s = s1 + s2;
I feel like doing s = s + s1 + s2 with the existing implementation.
Using friend operator overload should do the trick for you and is a common way to define binary operators, just add:
If you want it to remain a member, (which has downsides in some rare scenarios, and no upsides), you have to make the operator a
constfunction:Either of these will allow operator chaining. The reason your previous
s = s + s1 + s2was failing, is that thes + s1would execute and return a temporarysampleobject. Then, it would attempt to adds2to that sample. However, temporaries can only beconstreferences[1], and as such, can only useconstmember functions. Since youroperator+member function is not aconstfunction, you cannot use that function on theconsttemporary. Note that to make itconst, I had to rewrite it, since your version modifies the object on the left side of the+.[1]with exceptions aren’t particularly relevant here, namely rvalues