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.
Two operators = and & are already overloaded by default in C++. For example, to copy objects of the same class, we can directly use the = operator. We do not need to create an operator function. Operator overloading cannot change the precedence and associativity of operators.
Overloading the assignment operator (operator=) is fairly straightforward, with one specific caveat that we'll get to. The assignment operator must be overloaded as a member function. This will call f1. operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves.
The name of an overloaded operator is operator x, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.
Assignment Operators Overloading in C++ You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. Following example explains how an assignment operator can be overloaded.
Using friend operator overload should do the trick for you and is a common way to define binary operators, just add:
friend sample operator+(const sample& a, const sample& b); //in class
sample operator+(const sample& a, const sample& b) { //outside the class
return sample(a.x + b.x);
}
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 const
function:
sample operator+(sample s) const; //in class
sample sample::operator+(const sample& b) const { //outside the class
return sample(this->x + b.x);
}
Either of these will allow operator chaining. The reason your previous s = s + s1 + s2
was failing, is that the s + s1
would execute and return a temporary sample
object. Then, it would attempt to add s2
to that sample. However, temporaries can only be const
references[1], and as such, can only use const
member functions. Since your operator+
member function is not a const
function, you cannot use that function on the const
temporary. Note that to make it const
, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With