I have a Fraction class as following.
class Fraction
{
int num, den ;
public:
//member functions here
} ;
I read in some book, I think ‘effective c++’ that it is better to overload the addition operator as non member function. The reason given there was that it allows commutative addition.
This is the prototype of my overloaded function for addition operator.
Fraction operator + (const Fraction &obj, const int add_int) ;
Here, when i call it, I have to do it like this.
f1 + 2 ;
But it won’t work this way.
2 + f1 ;
For that i would have to write the function again and change the order of parameters in that.
I want to know that whether there is a method by which I can overload function a single time and perform commutative addition?
You can, but only if your class has an implicit constructor from the type you want to add to, so this would work:
Of course, this allows a usage that you didn’t actually mention you wanted, which is the ability to add two
Fractionobjects.I can’t imagine you would want to disallow that though.