0
include <typeinfo>    

vector<Console*> consoles;
Console* sony = new Sony();
cout << typeid(sony).name() << endl; // typeid name == 4Sony
consoles.push_back(sony);
cout << typeid(*consoles.back()).name() << endl; // typeid name == 7Console
Console* microsoft = new Microsoft();
consoles.push_back(microsoft);//the same happens with microsoft consoles

this is basically what I'm trying to do:

for(int i = 0; i < consoles.size(); i++){
    if(typeid(*consoles[i]).name() == typeid(Sony).name()){
        //cout << "it's a sony console" << endl;
    }
}

I can't do this because the typeid name of the console changes after I add it to the vector, so is there a way to make the typeid name of the console to stay the same after adding it to the vector?

Andre V
  • 13
  • 4
  • If what you want is to be able to distinguish the instances by types then maybe this question and answer could help further: http://stackoverflow.com/a/500495/1566187 – Ely Mar 09 '17 at 20:00
  • 1
    Probably your base class is non-polymorphic. Make sure it has at least one virtual function – M.M Mar 09 '17 at 20:04
  • I can't believe I forgot about polymorphism, that was the problem thanks – Andre V Mar 09 '17 at 20:10
  • Have you considered using [`dynamic_cast`](http://en.cppreference.com/w/cpp/language/dynamic_cast) instead? Something like :`if(dynamic_cast(consoles[i]) != nullptr)`. – François Andrieux Mar 09 '17 at 20:19

1 Answers1

0

Most probably the base class has no virtual methods, and thus is not polymorphic. typeid provides the dynamic type only for polymorphic classes, for non-polymorphic ones you'll only get the static type (the implementation detail behind this is that normally information about the dynamic type is brought through the vptr).

Still, this is not a big hassle, since, if you plan to store instances of derived classes through base class pointers and inspect their dynamic type you'll almost surely will want to have at least a virtual destructor (otherwise deleting an instance through the base class pointer will incur in undefined behavior).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • Wops, I just noticed that the problem was already solved in the comments... Well, I hope this will be useful at least to future visitors. – Matteo Italia Mar 09 '17 at 20:18