C++: is instance descendant of class

0 votes
asked Nov 11, 2010 by peter

Assume we have three classes A, B and C. B is derived from A and C is derived from B. Now we have a pointer that points to an object of class A. Due to Polymorphism it can actually point to instances of all three classes.

With typeid() i can check what type the pointer actually refers to. But I'm trying to determine if it points to any descendant of class B. That is to say I'm looking for some kind of IsDescendantOf(unkownclass, baseclass) function. Is there a why to do so in C++?

4 Answers

0 votes
answered Nov 11, 2010 by matthew-flaschen

Use dynamic_cast. It returns NULL on failure:

B* pb = dynamic_cast<B*>(pa);

You may find this MSDN article helpful.

0 votes
answered Nov 11, 2010 by kos

You can cast an object via dynamic_cast<TargetType*>(ptr) and then check if the result is null (cannot cast - not a descendant) or not.

0 votes
answered Nov 11, 2010 by flexo

You can also test this using template meta programming, at compile time. It even works if the classes in question do not have any virtual functions, which dynamic_cast won't.

template <typename D, typename B>
class is_derived_from {
   class No { };
   class Yes { No no[2]; };

   static Yes Test(B*);
   static No  Test(...);
   enum { inherits = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
   static bool is_derived() { return inherits; }

I think this is derived from one of the excellent GoTW series.

0 votes
answered Sep 15, 2017 by sergei

use std::is_base_of from <type_traits> and static_assert to check at compile time

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter