Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check pointer of inherited class?

Let's assume that we have two class: a polymorhpic class A and class B that inherits from class A. How can I check if a pointer of class A points to an object of class B?

like image 850
Nowax Avatar asked Feb 12 '23 23:02

Nowax


1 Answers

Assuming that the runtime type information (RTTI) is enabled, you can cast the pointer to B* using dynamic_cast, and see if you get a non-null value back:

A* ptr = ... // some pointer
if (dynamic_cast<B*>(ptr)) {
    // ptr points to an object of type B or any type derived from B.
}

Another way of doing this would be using typeid:

if (typeid(*ptr) == typeid(B)) {
    // ptr points to an object of type B, but not to a type derived from B.
}

Note: if you need to do this often, good chances are that your design can be improved.

like image 167
Sergey Kalinichenko Avatar answered Feb 15 '23 11:02

Sergey Kalinichenko