Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 969
Leedehai Avatar asked Jan 27 '23 17:01

Leedehai


1 Answers

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).

like image 150
user7860670 Avatar answered Jan 30 '23 13:01

user7860670