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/