Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

You can use dynamic_cast.

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

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

Not wanting to spoil the fun, but an initialized enum member in the base class would also do in case no RTTI is available.

I was thinking the other day, that in these classical OOP problems, one could also use a variant class, say:

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

These classes might all inherit, say from Animal, one would not need virtual functions in the implementation at all, but would need to check for the type, the instance of which the variant contains, at runtime.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top