Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a pointer points to a particular class C++ [duplicate]

Tags:

c++

pointers

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?

like image 258
lordlabakdas Avatar asked Aug 14 '12 11:08

lordlabakdas


People also ask

How do you validate a pointer?

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.

Can this pointer point to another class?

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.

How do you test the Nullptr?

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.

How do you check if a pointer points to an array?

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.


2 Answers

if(dynamic_cast<DerivedClass1*>(ptr))
{
  // Points to DerivedClass1
}
else if(dynamic_cast<DerivedClass2*>(ptr)
{
  // Points to DerivedClass2
}
like image 155
Aesthete Avatar answered Sep 24 '22 14:09

Aesthete


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.

like image 30
Ben Voigt Avatar answered Sep 25 '22 14:09

Ben Voigt