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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With