freinn
freinn

Reputation: 1079

How to know what type of object is pointing a base class pointer?

I have a base class named Cell (other class has a pointer to an object of this class), and 3 derivated classes CellA, CellB and CellC. When a cell is dead, the pointer points to Cell, in other case is alive (A,B or C). How to know what is pointing that pointer in this moment to act??

Upvotes: 0

Views: 230

Answers (3)

vatsa
vatsa

Reputation: 9

use dynamic_case or typeid() to know the object at runtime...

Upvotes: 0

Alok Save
Alok Save

Reputation: 206616

In case your classes are polymorphic You can use dynamic_cast.
dynamic_cast allows you to safely downcast pointers.
In your case, You can use dynamic_cast to check if the Base class pointer is pointing to a derived instance, dynamic_cast can report you that information.

Upvotes: 1

AlexTheo
AlexTheo

Reputation: 4184

Maybe you need a little bit different logic, take a look on states design pattern I think it could help you. Normally the casting is a bad thing and should be avoided. If you need a casting then you probably have a design issue....

Good Luck

Upvotes: 1

Related Questions