Determining if One Object's Class Is a Subclass of Another - C++ Class

C++ examples for Class:dynamic_cast

Description

Determining if One Object's Class Is a Subclass of Another

Demo Code

#include <iostream>
#include <typeinfo>

using namespace std;

class Base {/* ww w  .ja va  2  s .  com*/
public:
   virtual ~Base() {} // Make this a polymorphic class
};
class Derived : public Base {
public:
   virtual ~Derived() {}
};

int main() {

   Derived d;

   // Query the type relationship
   if (dynamic_cast<Base*>(&d)) {
      cout << "Derived is a subclass of Base" << endl;
   }
   else {
      cout << "Derived is NOT a subclass of Base" << endl;
   }
}

Result


Related Tutorials