Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page