一、代码
class A {
public:
A() {
cout << "A construction." << endl;;
virfun();
};
virtual ~A() {
cout << "A disconstruction." << endl;
virfun();
};
virtual void virfun() {
cout << "Base virtual function." << endl;
}
};
class B:public A {
public:
B() {
cout << "B construction." << endl;
virfun();
};
~B() {
cout << "B disconstruction." << endl;
virfun();
};
void virfun() {
cout << "Derived virtual function." << endl;
}
};
int main() {
A* b = new B();
delete b;
}
二、运行结果
三、结论
虚表在编译阶段就完成构建,所以无论构造函数还是析构函数,都可以调用虚函数,且调用的虚函数都是类本身的虚函数版本。