Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javas Class<?> equivalent in C++

Tags:

java

c++

So I'm learning C++ and want to write an entity-component system. For that I need to know what type a component has when i add it to the entity. In java i would just do something like this:

Class<?> someClass = myComponent.class;

Is there something equivalent I can do in C++? I tried typeid(myComponent) but that doesn't work in situations like this.

ExtComponent* extended = new ExtComponent();
Component* base = dynamic_cast<Component>(extended);
std::cout << typeid(base).name();

This returns "class Component" but i would want something that returns "class ExtComponent" in such a situation. How do I do this.

like image 958
qwipo Avatar asked Feb 07 '23 21:02

qwipo


1 Answers

If I understand you correctly you want to get dynamic type of object. (not type of variable itself, but to what that variable (really) refers)

Typeid will work because:

N3337 5.2.8/2:

When typeid is applied to a glvalue expression whose type is a polymorphic class type (10.3), the result refers to a std::type_info object representing the type of the most derived object (1.8) (that is, the dynamic type) to which the glvalue refers[...]

So, just add some virtual function (of alternatively virtual base class) to make, and their will do what you want.

Also you'll have to apply typeid to object, not pointer (because that would return type_info for pointer, not object):

Base *b = new Base;
...
typeid(*b); //not typeid(b)
like image 120
PcAF Avatar answered Feb 20 '23 04:02

PcAF