typeid() returning wrong type

52 views Asked by At

I understand that when RTTI is not enabled or the class in question isn't virtual that I could expect the behavior I'm getting, but in this case I don't understand why I'm not getting the right type. typeid() should at runtime determine the type of something, say by dereferencing the pointer to it, it should return the right "BorderedWindow" here, no?

#include <iostream>
#include <string>

class Window
{public:
    Window()
    {
        std::cout << getClassType() << '\n'; // PRINTS "Window"

    }

    std::string getClassType()
    {
        return typeid(*this).name();
    }

    virtual ~Window() {}
};

class BorderedWindow : public Window
{public:
    BorderedWindow() : Window() 
    {
        std::cout << getClassType() << '\n';  // PRINTS "BorderedWindow"
    }
};

int main()
{
    BorderedWindow* b = new BorderedWindow;
}

I understand that when getClassType() is called from Window's constructor that it passes the pointer to Window, but typeid() should determine that it's of type BorderedWindow, shouldn't it? Because it's done at runtime checking the virtual table information. Essentially I expected that the type could be accurately figured out whenever passing the pointer to the class object to typeid().

0

There are 0 answers