C++构造函数中调用虚函数

时间:2022-09-02 20:03:26

构造函数中调用虚函数时,父类构造函数调用的是父类的虚函数,子类构造函数调用的是子类的虚函数。

父类构造函数并没有遵循虚函数调用机制,调用具体子类的虚函数,是因为调用父类构造函数时,子类对象还没有构造好。


#include <stdio.h>

class Base
{
public:
Base(){printf("Base ctor\n");g();};
virtual void f(){printf("Base::f\n");};
void g() {
f();
};
};

class Derived:public Base
{
public:
Derived(){printf("Derived ctor\n"); f();};
void f(){printf("Derived::f\n");};
};

int main()
{
Derived d;
d.g();

return 0;
}