Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is instance descendant of class

Tags:

c++

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++?

like image 240
Peter Avatar asked Dec 07 '22 00:12

Peter


1 Answers

Use dynamic_cast. It returns NULL on failure:

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

You may find this MSDN article helpful.

like image 110
Matthew Flaschen Avatar answered Jan 03 '23 04:01

Matthew Flaschen