内容来源: 传智播客
c++面试中常常会问到一个问题:
通过子类对象,在父类构造函数中调用虚函数,能实现多态吗?
#iinclude<iostream>
using namespace std;
class A {
public:
int a;
A(int a) {
this->a = a;
print();
}
virtual void print() {
cout << "执行基类成员函数" << endl;
cout << a << endl;
}
};
class B :public A {
public:
int b;
B(int a, int b) :A(a) {
this->b = b;
print();
}
virtual void print() {
cout << "执行子类成员函数" << endl;
cout << b <<endl;
}
};
int main() {
B b(1, 2);
}
通过上述代码,上述问题转化成: 通过B类生成对象b,在初始化时,需要调用构造函数,根据构造函数的调用规则,需要先调用父类A的构造函数,但是父类构造函数中有虚函数print, 这时他到底会调用父类的print函数, 还是会调用子类的构造函数(多态)
明确上述问题,,需要知道对象中VPTR指针的指向问题,