How to check the pointer of an inherited class?

Suppose we have two classes: a polymorphic class A and a class B that inherits from class A. How can I check if the pointer of a class A points to an object of class B?

+4
source share
3 answers

Assuming runtime information (RTTI) is included, you can direct the pointer to B*with dynamic_castand see if you return a non-zero value:

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 to do this would be to use 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, there is a good chance your design can be improved.

+6
source

dynamic_cast.

void foo(A* aPtr);
{
   if ( dynamic_cast<B*>(aPtr) != NULL)
   {
     // Got a B.
   }
}

void bar()
{
   B b;
   foo(&b);
}
+2

, enum , RTTI.

I thought the other day that in these classic OOP problems, you can also use a class variant, say:

variant<Tiger, Cat, Frog, Dog> object;

These classes can be inherited, say, from Animal, virtual functions are not needed at all in the implementation, but it will be necessary to check the type whose instance is contained variantat run time.

0
source

Source: https://habr.com/ru/post/1540777/


All Articles