static_cast parent class to child class C++

こ雲淡風輕ζ 提交于 2020-01-17 05:13:13

问题


Output of this program is "Method B". How can an instance of the parent object call the child class's function through a static_cast?

To make things more confusing, if I make method() virtual, then this code outputs "Method A".

Can anyone explain what is happening here?

class A {
public:

    void method() {
        cout << "Method A" << endl;
    }

};

class B : public A {
public:
    void method() {
        cout << "Method B" << endl;
    }
};

int main() {
    A a;
    B* bptr = static_cast<B*>(&a);
    bptr->method();
}

来源:https://stackoverflow.com/questions/36653061/static-cast-parent-class-to-child-class-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!