Search code examples
c++typeidtypeinfo

Why is typeid always returning false?


So I have to make a text based video game for a project. I made a class called "tile" and then a subclass called "wall." I then made an array of tiles shown below. The center tile, B2 is a wall. When I compare typeid(B2)==typeid(wall) it returns false even though tile B2 is of type wall. The class, "fighter" has an x and a y component.

  //Initiate map
    const int rows = 3;
    const int cols = 3;
    tile A1, A2, A3, B1, B3, C1, C2, C3;
    fighter wizard(1, 2, 6, ft::mage, 100);
    C3 = tile(wizard, "There's all this magic stuff everywhere.");
    wall B2= wall("A wall blocks your path.");
    tile map[rows][cols] =  {{A1, A2, A3},
                             {B1, B2, B3},
                             {C1, C2, C3}};
...

fighter player1(0, 0, 0, ft::warrior);

...

string input = "";
while(input!="quit")
{ 
    cin >> input;
    if (input == "left") {
        if (typeid(map[player1.y][player1.x - 1]) == typeid(wall))
            cout << map[player1.y][player1.x - 1].scene;

Solution

  • tile map[rows][cols]
    

    Stores tile objects. If you were to inspect these objects you will find that they are of class tile. Not the type of the original B2 object, wall. So

    if (typeid(map[player1.y][player1.x - 1]) == typeid(wall))
    

    will always compare tile == wall.

    If you are interested in preserving the dynamic type you need to use (smart) pointers or any way that references the original object. These objects needs to have a dynamic type/have virtual functions.

    See also What is dynamic type of object