Question

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.

Was it helpful?

Solution

Redesign your classes. Chances are inheritance isn't what you need here.

Rationale: If you have a Foo pointer somewhere, then its owner shouldn't need to know whether it points to Foo object or FooB or any other derived object - it only uses Foo functionality, ignorant of the implementation. (That's how polymorphism works in general.)

In other words: If you have a Foo pointer and its user depends on functionality only in FooB, then that pointer should be of type FooB in the first place.

OTHER TIPS

If you want to only use Foo pointer, and call Bar methods, Foo must implement the Bar interface. It's the only way to let your compiler know that the Foo object can used this method, without the cast of course.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top