为什么构造函数忽略重写的虚函数

Why do constructors ignore overriden virtual functions?

本文关键字:函数 重写 构造函数 为什么      更新时间:2023-10-16

下面是一个例子:

struct parent {
    int a;
    virtual void stuff() { a = 5; } //variant A
    void roundabout() { stuff(); }
    parent() { stuff(); }
};
struct child : parent {
    void stuff() override { a = 6; } //variant B
    child() : parent() {}
};

和用法

child c;  //calls variant A
auto p = reinterpret_cast<parent*>(&c);
c.stuff(); //calls variant B
c.roundabout(); //calls variant B
p->stuff(); //calls variant B
p->roundabout() //calls variant B

所以在构造之后,我从类内部或外部调用 stuff() 的任何方式,都没有明确说明 parent::stuff() 我得到了 child::stuff(),正如预期的那样。

一个例外是父构造函数仍然调用 parent::stuff(),即使它由子构造函数触发。这真的很烦人,因为我必须在构造函数调用的函数中包含额外的逻辑,以使它们按预期运行。为什么会这样?

除非父实例已存在,否则子项的实例不能存在。因此,在父级的构造函数中,不能存在子项的实例。那么,如果没有孩子存在,你怎么能打电话给child::stuff呢?