c++ - 从子构造函数/析构函数调用纯虚函数

标签 c++

class A{
virtual void setEnable(bool enable) = 0;
};

class B : A{
    B() {
        setEnable(true);
    }
    ~B() {
        setEnable(false);
    }
    bool enable_ = false;
    
void setEnable(bool enable) override {
    enable_ = enable;
}
};

我的理解是否正确:只有在构造函数退出后,B::setEnable 函数才会添加到 vtable 中,这是未定义的行为?

最佳答案

Am I correct in understanding that the B::setEnable function will be added to the vtable only after the constructor exits and this is undefined behavior?

没有。在 A 构造函数体内,A 对象已完全初始化,但 B 对象尚未初始化。从构造函数调用虚函数的问题在于,它会不直观地调用构造函数所属类型的方法,而没有多态行为。

关于c++ - 从子构造函数/析构函数调用纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68839790/

相关文章:

c++ - 在 C++ 中使用#undef

c++ - SDL2 C++ 捕获渲染器动画/ Sprite 的视频

c++ - C++ 中 placement new 执行的完整操作列表是什么?

c++ - .o 生成具有不同规则的 Makefile

C++ 导入和重命名/重新保存图像

c++ - 检查矩阵相乘结果的方法?

c++ - c++ client session 和 c_api TF_Session 以及 tensorflow 源代码中的 core/public/session 之间有什么关系?

c++ - 如何将元组扩展为可变参数模板函数的参数?

c++ - 错误 : invalid types 'double*[double]' for array subscript

C++ 控制台应用程序,SetWindowsHookEx,永远不会调用回调