Leedehai
Leedehai

Reputation: 3950

C++ polymorphism: how to test if a class derived from another base class?

Sorry for the title's wording; I don't know how to make it better. But the gist of my question is this:

#include <iostream>
using namespace std;

class Base {};
class Base2 {};
class C : public Base, public Base2 {};
class D : public Base {};

void isDerivedFromBase2(Base *p) {
    if (...) { /* test whether the "real object" pointed by p is derived from Base2? */
        cout << "true" << endl;
    }
    cout << "false" << endl;
}
int main() {
    Base *pc = new C;
    Base *pd = new D; 
    isDerivedFromBase2(pc); // prints "true"
    isDerivedFromBase2(pd); // prints "false"

    // ... other stuff
}

How do I test if an object, represented by its base class pointer Base *, is derived from another base class Base2?

Upvotes: 4

Views: 373

Answers (2)

Aganju
Aganju

Reputation: 6395

This sounds like an X-Y problem.

The need for RTTI (or the need to test an object for which class it is derived from) is typically a sign for a bad design - you simply should not ever need such a test/information.
If the hierarchy is well designed, virtual functions take on the role of these tests.

To find out what is not well-designed, ask yourself 'what I am going to do with the information once I have it?' The answer is always something of the kind 'I'll make an if/switch/... to treat them differently'; and the correct solution is to treat them the same way - call a virtual method, and each object carries the knowledge of the right virtual method which knows what it needs to get done.

Upvotes: 0

user7860670
user7860670

Reputation: 37548

You can perform dynamic_cast like this:

 if (dynamic_cast<Base2 *>(p)) {

online_compiler

Unlike approach with typeid this one does not require an extra header to be included, however it relies on RTTI as well (this implies that these classes need to be polymorphic).

Upvotes: 8

Related Questions