8.7. Determining if One Object’s Class Is a Subclass of Another

Problem

You have two objects, and you need to know if their respective classes have a base class/derived class relationship or if they are unrelated.

Solution

Use the dynamic_cast operator to attempt to downcast from one type to another. The result tells you about the class’s relationships. Example 8-7 presents some code for doing this.

Example 8-7. Determining class relationships

#include <iostream>
#include <typeinfo>

using namespace std;

class Base {
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;
   }
}

Discussion

Use the dynamic_cast operator to query the relationship between two types. dynamic_cast takes a pointer or reference to a given type and tries to convert it to a pointer or reference of a derived type, i.e., casting down a class hierarchy. If you have a Base* that points to a Derived object, dynamic_cast<Base*>(&d) returns a pointer of type Derived only if d is an object of a type that’s derived from Base. If this is not possible (because Derived is not a subclass, directly or indirectly, of Base), the cast fails and NULL is returned if you passed dynamic_cast a pointer to a derived object. If it is a reference, then the standard exception ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.