The assignment operator can be declared as
T& operator= (const t&);
in a class, but the arithmetic operators cannot be defined that way. It has to be friend function. I don't understand why? Can you please explain ?
coperator-overloading
The assignment operator can be declared as
T& operator= (const t&);
in a class, but the arithmetic operators cannot be defined that way. It has to be friend function. I don't understand why? Can you please explain ?
Best Answer
It is not mandatory that arithmetic operators should be friend
Well you can define like this:
The
a + b
is really a syntax sugar, the compiler will expand it toa.operator+(b)
. The previous sample will work if all your objects are MyClass instances, but will not work if you have to operate with others types, ie1 + a
, will not work, this can be solved by using friends.This has to be done when the left hand side of the + operator is not a class, or it is a class but you can't add operator + to its definition.