Sign in to follow this  
Lode

OO and dynamic cast question

Recommended Posts

Hi, I often have the habbit in C++ to make a class inherit from multiple abstract classes and using dynamic casts on incoming objects to check if they inherit from a certain interface or not. E.g. if an object inherits from an interface "IHelpTextProvider", some GUI or whatever will display a help text for that object, otherwise it'll treat it as an object that has no help text. Since C++ with its multiple inheritance is rare (Java has it but not initially and it's not "true" multiple inheritance, just interfaces), I have a qustion about this: Is this a good "pattern" from OO perspective or not? If not, what alternatives are there? If not, why not? What does the true OO philosophy have to say here?

Share this post


Link to post
Share on other sites
I think the way you're doing it is OK, but it's still vastly preferable to avoid it. I'm sure someone will come along with a way to refactor your example so you don't need it.

Share this post


Link to post
Share on other sites
I'm fine with the concept of multiple inheritance from interface classes, I see it used in C++ but the fact that C++ is a multi-paradigm language frequently reduces the need for this sort of thing also.

As for true OO, I suppose there is an element of whether or not you're violating the Single Responsibility Principle, one might argue that something inheriting from IHelpTextProvider has thereby been assigned its singlular responsibility and inheriting from anything further than that is probably just going to add more.

The use of dynamic casts is a bit funky though, if your function accepted an IHelpTextProvider then you wouldn't need to cast, or if you're using polymorphism then you could just inspect a getHelpText() function to remove the need to cast.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this