u.sairam1248
u.sairam1248

Reputation: 1

operator overloading with friend and member function

With in a class if we are using both member function and friend function to overload + operator its giving an error that ambiguous overload for ‘operator+’ how to resolve

Upvotes: 0

Views: 174

Answers (2)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

You could have a member and non-member overload of operator+, if you really wanted to.

Foo a, b;
a.operator+(b); //call member function
operator+(a, b); //call non-member function

It ruins the whole point of operators, though, since you have to actually write out the method call.


Side note: non-member operator+ doesn't need to be a friend function. It's easily written as:

Foo operator+ (Foo lhs, const Foo& rhs)
{
    return lhs += rhs;
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206577

I would suggest implementing it as a non-member function. That way, you can overload the function with other combinations. As an example, let's say you have a class Point and another class Vector (a gometric vector, not the std::vector).

You can overload

Point operator+(Point const&, Vector const&);
Point operator+(Vector const&, Point const&);

If you implement it as a member function, you implement only one of them in a class. To implement both, you'll have to implement the first one as a member function of Point and the second one as a member function of Vector.

Upvotes: 1

Related Questions