I have a base class called Object. PhysicsObject inherits from Object. Ball inherits from PhysicsObject, and SoftBall inherits from Ball. Something like this:
Object
|
PhysicsObject
|
Ball
|
SoftBall
I have a method called foo() that is declared virtual in Object (given an implementation, so not pure virtual), then declared and implemented as virtual again in PhysicsObject and Ball. Finally, SoftBall implements foo() again without declaring it as virtual.
If I have an Object* that points to a SoftBall, will SoftBall’s version of foo() be called? If not, is there any way to achieve this effect? Basically, does this aspect of polymorphism still work over more than one level of inheritance?
Yes
C++ defines methods as virtual if the corresponding overload is virtual in the base class (unlike other OO languages, where overrides have to be marked explicitely).
http://codepad.org/pL09QWNN
Note that with some more ingredients you can get really funky:
Try to predict what gets printed here. It get’s a lot more fun once you mixin:
I remember reading quite a lot of more and less horrendous examples in the form of trivia question I hope to never encounter in an interview. Although I know what I’d answer: “If you have code like this, I’m not sure I want the job”?.
You could go looking on Herb Sutter, Scott Meyer, and you’ll be amazed what pitfalls lurk in our otherwise-so-civilized-nice-little-language-fondly-referred-to-as C++