Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Identifying the type of the object

Tags:

c++

c++11

I'm curious what constructs or language features, available in both the current C++ as well as in C++11, can be used to deduce the type of an object. An example:

class Base {
};

class DerivA
    : public Base {
};

class DerivB
    : public Base {
};

void foo(Base* obj) {
    // Identify if `obj` is a `DerivA` or a `DerivB`
}

This is an oversimplification. It would appear that rather than having a way to identify the type, the best solution is to have overloads of the function for the two derived types and do away with the base class.

My real use case is one where one class is not interested in the exact type of the object (ie. just needs an implementation of Base) and another class needs to know exactly what implementation of Base the first class is using.

This happens in a component-based game entity system. The base would be an EntityState and its derived types are StandingState, DeadState, etc. Class Entity is the one that only needs a generic EntityState object and class EntityRepresentation needs to know exactly what state the entity is in to decide whether to draw the "standing" animation or the "dead" animation, or whatever.


Edit: Of course, if possible, I'd like to implement the game in such a way that not even the entity representation needs to know the type of the entity state. If there's a way to do that, then I'd use it. :) I'll look into the visitor pattern.

like image 443
Paul Manta Avatar asked Dec 17 '22 12:12

Paul Manta


2 Answers

You can use dynamic_cast for that:

if(DerivA * derivA = dynamic_cast<DerivA*>(obj)){
    // it is a DerivA
}
like image 105
tibur Avatar answered Dec 19 '22 02:12

tibur


Two ways:

If your classes are polymorphic use, dynamic_cast

or else you can use typeid

Usage of typeid

#include <typeinfo.h>


typeid(YourClass).name()

Usage of dynamic_cast

DerivA& dynamic_cast<DerivA&> (object);
DerivA* dynamic_cast<DerivA*> (object);

there must be least one virtual function in Base class to make dynamic_cast work or you will get compilation errors.

If you try to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. For a similar situation in case of references the cast will throw a bad_cast exception.

like image 31
Alok Save Avatar answered Dec 19 '22 03:12

Alok Save