In C++, I have a class FooA and a class FooB that both are child classes of a base class Foo. FooB has to implement interface Bar. If I only have a Foo pointer to a FooB and wish to use FooB’s Bar methods, I would have to do a cast. However, that seems to violate polymorphism.
I’m wondering if there’s a better approach to allow FooB to implement the Bar interface without forcing all Foo derived classes to also implement Bar.
Redesign your classes. Chances are inheritance isn’t what you need here.
Rationale: If you have a
Foopointer somewhere, then its owner shouldn’t need to know whether it points toFooobject orFooBor any other derived object – it only usesFoofunctionality, ignorant of the implementation. (That’s how polymorphism works in general.)In other words: If you have a
Foopointer and its user depends on functionality only inFooB, then that pointer should be of typeFooBin the first place.