Calling virtual function of derived class from base class constructor?

前端 未结 4 1533
时光取名叫无心
时光取名叫无心 2020-12-11 01:24

I´m trying to accomplish the same which is described in a previous question:

virtual function call from base class

But, my real question is:

What if

相关标签:
4条回答
  • 2020-12-11 01:30

    The virtual mechanism does not work in the constructors, so if you call even a virtual function from a base class constructor you will always end up calling the functions of the base class only. There are a few reasons why the virtual funcs do not work in the ctors:

    1. While in the constructors the object has not been created fully.
    2. ctors calls are resolved at compile time only, so they actually don't have any runtime dependency, so no use of virtual functions.
    3. Unlike other functions ctors and dtors are not inherited, so every class has its own set of ctors and dtors, so there is no chance of overriding.
    0 讨论(0)
  • 2020-12-11 01:31

    Even though it's a virtual function, the base's version will get called since the derived class isn't fully constructed yet. The base class constructor is called before the derived class constructor, so if the derived virtual function were to get called, it would be with an incompletely-initialized instance - a possible (probably) recipe for disaster.

    0 讨论(0)
  • 2020-12-11 01:32

    When your base class constructor is called, only the vtable for the base class is setup, so any virtual function calls will apply only to base class methods.

    When the derived class constructor is called, calling a virtual function will call the derived class override, if any.

    0 讨论(0)
  • 2020-12-11 01:50

    It will Base::g(). See this FAQ for explanation.

    0 讨论(0)
提交回复
热议问题