Possible Duplicate:
Finding the type of an object in C++
I have a question with checking pointers to see if they conform to a particular derived class and take necessary action.
Lets say I currently have 2 derived classes DerivedClass1
and DerivedClass2
and the base class BaseClass
. I would like to check the following action.
Ptr<BaseClass> ptr;
if (ptr points to DerivedClass1)
{
action1
}
else
{
action2
}
How do I check for ptr points to a particular DerivedClass?
initialize all pointers to zero. if you cannot guarantee a pointer is valid, check that it is non-0 before indirecting it. when deleting objects, set the pointer to 0 after deletion. be careful of object ownership issues when passing pointers to other functions.
It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible.
To test if a pointer is a nullptr , you can compare it by using the = and the != operator. This is useful when we are using pointers to access objects.
Using just raw pointers there's no way to know if they point to an array or a single value. A pointer that is being used as an array and a pointer to a single values are identical - they're both just a memory address - so theres no information to use to distinguish between them.
if(dynamic_cast<DerivedClass1*>(ptr))
{
// Points to DerivedClass1
}
else if(dynamic_cast<DerivedClass2*>(ptr)
{
// Points to DerivedClass2
}
If BaseClass
is polymorphic (contains virtual functions), you can test:
if (dynamic_cast<DerivedClass1*>(ptr.get()))
But usually you should use dynamic dispatch as unwind suggests, possibly a Visitor pattern, for this sort of thing. Littering your code with dynamic_cast
makes it hard to maintain. I use dynamic_cast
almost NEVER.
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