Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out what type of object a pointer points to in C++?

Let's say I have class SuperClass { public: int a; } and class SubClass : SuperClass { public: int b; } and I took a pointer to an instance of the SubClass SubClass *subPointer and addressed that pointer to a SuperClass pointer SuperClass *superPointer = subPointer. Now of course I can always cast the superPointer object to a pointer of SubClass because the only thing it stores is an adress. But how would I know if the object superPointer is pointing to an instance of SubClass or is just a SuperClass pointer?

like image 829
Monet R. Adams Avatar asked Dec 05 '22 10:12

Monet R. Adams


1 Answers

You usually don't want to use typeid for this.

You usually want to use dynamic_cast instead:

if (SubClass *p = dynamic_cast<SubClass *>(SuperClassPtr))
    // If we get here (the `if` succeeds) it was pointing to an object of 
    // the derived class and `p` is now pointing at that derived object.

A couple of notes though. First of all, you need at least one virtual function in the base class for this to work (but if it doesn't have a virtual function, why are you inheriting from it?)

Second, wanting this very often tends to indicate design problems with the code. In most cases, you want to define a virtual function in the base class, which you (if necessary) override in the derived class to do whatever's needed so you can just use a pointer to the base class throughout.

Finally, as it stands right now, most of the conversions will fail -- you've used the default (private) inheritance, which prevents the implicit conversion from derived * to base * that you'd normally expect to see happen (you probably want class SubClass : public SuperClass).

like image 93
Jerry Coffin Avatar answered Dec 06 '22 23:12

Jerry Coffin