OO and dynamic cast question

Started by
1 comment, last by dmatter 14 years, 11 months ago
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?
Advertisement
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.
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.

This topic is closed to new replies.

Advertisement