Virtual function invocation from constructor

这一生的挚爱 提交于 2019-12-24 04:40:54

问题


Maybe I am wrong, but this seems to be a very basic question. Suddenly my inheritance chain stopped working. Writing a small basic test application proved that it was me that was wrong (so I can't blame the compiler).

I have a base class, with the default behavior in a virtual function. A child class derives from that and changes the behavior.

#include <iostream>

class Base
{
public:
    Base() { print(); }
    ~Base() {}

protected:
    virtual void print() { std::cout << "base\n"; }
};

class Child : public Base
{
public:
    Child() {}
    ~Child() {}

protected:
    virtual void print() { std::cout << "child\n"; }
};

int main()
{
    Base b;
    Child c;
}

This prints:

base
base

When a Child instance is created, why is Base::print() called? I thought that by using the virtual keyword, the function can be replaced for the derived class.

At what point did I get myself confused?


回答1:


You are calling a virtual method in the constructor, which is not going to work, as the child class isn't fully initialized yet.

See also this StackOverflow question.




回答2:


Although your current problem is the virtual method call from a constructor that others have mentioned, I noticed that you didn't make the destructors virtual. That's normally a bad thing. In your case, the destructors are nops and there are no members that are objects with destructors,... but if your code changes then it's easy for bad things to happen.



来源:https://stackoverflow.com/questions/507043/virtual-function-invocation-from-constructor

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