Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ overloaded method in derived class

I have the following question:

Assume base class A with method:

A& operator+(A& a) {...}

I also have a derived class B which overloads (or at least it should so) this method:

A& operator+(B& b) {...}

The problem is that if i want to call something like: b + a (where b is of type B and a of type A) i get a compile error. (error C2679: binary '+' : no operator found which takes a right-hand operand of type 'A' (or there is no acceptable conversion)).

Shouldnt that call the base class method? (it looks like it overrides the method..) If not, why? Is there a way to fix this (dont tell me to overload the method in B with A&)

Sorry i dont give examples in formated text, but i dont know how to format it.

Thanks in advance!

PS Im using Visual studio 2010 beta.

like image 992
George Avatar asked Oct 25 '25 22:10

George


2 Answers

No, it won't call the base class function. Class B has an operator+, it doesn't take the correct parameter, end of story.

You can define operator+ as a free function, not in any class. Perhaps a friend, if it needs to access private data:

A operator+(const A &lhs, const A &rhs) { ... }
B operator+(const B &lhs, const B &rhs) { ... }

Then b + a will call the first operator, as will a + b. b + b will call the second.

Alternatively, you could "un-hide" the base class implementation, by putting this in class B:

using A::operator+;

it's probably best not to, though. Most operators work better as free functions, because then you get automatic conversions on both operands. C++ never performs conversions on the LHS of a member function call.

Btw, operator+ almost certainly should return by value, not by reference, since an automatic (stack) variable no longer exists once the function returns. So the caller needs to be passed a copy of the result, not a reference to it. For this reason operator+ and inheritance aren't a great mix, although it can probably work as long as the caller knows what they're doing.

like image 153
Steve Jessop Avatar answered Oct 27 '25 12:10

Steve Jessop


The problem is called hiding - a member function in a derived class hides functions with the same name in the base class. In this case you can't access A::operator+(A&) because it's being hidden by B::operator+. The way to fix this is to define B::operator+(A&), and possibly have it call the base class function.

Edit: There's a section in the C++ FAQ Lite that goes into more detail about this problem and offers another possible solution, namely the using keyword.

like image 33
Mark Ransom Avatar answered Oct 27 '25 12:10

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!