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?
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
).
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