C++虚函数与多继承
虚函数
C++用虚函数实现运行时多态,虚函数的实现是由两个部分组成的,虚函数指针与虚函数表。
虚函数指针(vptr)是指向虚函数表的指针,在一个被实例化的对象中,它总是被存放在该对象的地址首位。而虚函数表(vtbl)用于保存类包含的虚函数指针列表:
class Base {
public:
virtual void f() {
std::cout << "Base::f()" << std::endl;
}
private:
int n;
};
int main() {
Base* base = new Base;
return 0;
}
单继承下虚函数的内存布局
在单继承中,子类覆盖父类的虚函数,其实只需要在子类对应的虚函数表中覆盖对应的虚函数指针即可:
class Base {
public:
virtual void f() {
std::cout << "Base::f()" << std::endl;
}
private:
int n;
};
class Derived : public Base {
public:
void f() override {
std::cout << "Derived::f()" << std::endl;
}
virtual void k() {
std::cout << "Derived::k()" << std::endl;
}
private:
int h;
};
int main() {
Derived* derived= new Derived;
return 0;
}
多继承下虚函数的内存布局
class Base1 {
public:
virtual void f() {
std::cout << "Base1::f()" << std::endl;
}
private:
int n;
};
class Base2 {
public:
virtual void g() {
std::cout << "Base2::g()" << std::endl;
}
private:
int m;
};
class Derived : public Base1, public Base2 {
public:
void f() override {
std::cout << "Derived::f()" << std::endl;
}
void g() override {
std::cout << "Derived::g()" << std::endl;
}
virtual void k() {
std::cout << "Derived::k()" << std::endl;
}
private:
int h;
};
int main() {
Derived* derived= new Derived;
return 0;
}