多态实现方式是虚函数和虚函数表的覆盖。
#include <iostream>
#include <string>
using namespace std;
class Base {
public:
virtual void Action() {
cout << "Base function action" << endl;
}
};
class Derived1 : public Base {
void Action() {
cout << "Derived1 function action" << endl;
}
};
class Derived2 : public Base {
void Action() {
cout << "Derived2 function action" << endl;
}
};
void TakeAction(Base& base) {
base.Action();
}
void example() {
Derived1 Der;
TakeAction(Der);
}
int main() {
example();
return 0;
}
在此案例中,Base类有一个虚函数,这个虚函数指向了一个虚函数表
同时继承它的子类也会有一个虚函数表,当子类的虚函数表存在时,子类的虚函数表会覆盖父类的虚函数表,从而实现多态。
此时base的布局如下
class Base size(4):
+---
0 | {vfptr}
+---
Base::$vftable@:
| &Base_meta
| 0
0 | &Base::Action
Base::Action this adjustor: 0
Derived1布局如下
class Derived1 size(4):
+---
0 | +--- (base class Base)
0 | | {vfptr}
| +---
+---
Derived1::$vftable@:
| &Derived1_meta
| 0
0 | &Derived1::Action
但是如果Base中的函数不是虚函数,那么此时继承类的布局如下:
class Derived1 size(1):
+---
0 | +--- (base class Base)
| +---
+---