我已经阅读了关于 vtable 并理解了指向基类和派生类对象的基类指针的概念。有人可以解释当基类和派生类都是对象并且派生类对象分配给基类对象时如何创建vtable的情况。以下示例中的案例 3
#include <iostream>
#include <exception>
using namespace std;
class Base
{
public:
virtual void function1() { cout<<"Base - func1"<<endl; }
virtual void function2() { cout<<"Base - func2"<<endl; }
};
class Derived1: public Base
{
public:
virtual void function1() { cout<<"Derived1 - func1"<<endl; }
};
class Derived2: public Base
{
public:
virtual void function2() { cout<<"Derived2 - func2"<<endl; }
};
int main ()
{
// Case 1
Base* B1 = new Derived1();
B1->function1();
B1->function2();
// Case 2
cout<<endl;
Base* B2 = new Derived2();
B2->function1();
B2->function2();
// Case 3
cout<<endl;
Base B3;
Derived1 D1;
B3=D1;
B3.function1();
B3.function2();
}
输出:
Derived1 - func1
Base - func2
Base - func1
Derived2 - func2
Base - func1
Base - func2