虚继承

  1. 内存布局:Base1,Base2各自有自己的虚表,因为自己类中有自己的虚函数。

#include<iostream>
using namespace std;
typedef void(*Fun)();
class Base
{
public:
	virtual void fun1()
	{
		cout << "Base::fun1()" << endl;
	}

public:
	int _b;
};
class Base1 :virtual public Base
{
public:
	virtual void fun1()
	{
		cout << "Base1::fun1()" << endl;
	}
	virtual void fun3()
	{
	}
public:
	int _b1;
};
class Base2 :virtual public Base
{
public:
	virtual void fun1()
	{
		cout << "Base2::fun1()" << endl;
	}
	virtual void fun2()
	{
	}
public:
	int _b2;
};
class Derive :public Base1, public Base2
{
public:
	virtual void fun1()
	{
		cout << "Derive::fun1()" << endl;
	}
public:
	int _d;
};
void PrintVTable(int *ptr)
{
	for (int i = 0; ptr[i] != 0; ++i)
	{
		Fun f = (Fun)ptr[i];
		f();
	}
}
int main()
{
	Derive b1;
	b1._b1 = 2;
	b1.Base1::_b = 1;
	b1._b2 = 3;
	b1._d = 4;
	/*int *p1=(int *)(*(int*)&b1);
	PrintVTable(p1);

	cout<<sizeof(Base1)<<endl;
	int *p2=(int*)(*(int*)((int)&b1+sizeof(Base1)));
	PrintVTable(p2);*/
	system("pause");
	return 0;
}

各种继承内存布局(虚表)_虚继承虚表


2.子类中有虚函数,所以父类中必须创建虚表指针

class Base1 :virtual public Base

{

public:

virtual void fun1()

{

cout << "Base1::fun1()" << endl;

}

public:

int _b1;

};

class Base2 :virtual public Base

{

public:

virtual void fun1()

{

cout << "Base2::fun1()" << endl;

}

public:

int _b2;

};

class Derive :public Base1, public Base2

{

public:

virtual void fun1()

{

cout << "Derive::fun1()" << endl;

}

virtual void fun2()

{


}

public:

int _d;

};

各种继承内存布局(虚表)_虚继承虚表_02

3.父类中无虚函数,在子类中创建虚表指针

class Base

{

public:

public:

int _b;

};

class Base1 :virtual public Base

{

public:

virtual void fun1()

{

cout << "Base1::fun1()" << endl;

}

public:

int _b1;

};

class Base2 :virtual public Base

{

public:

virtual void fun1()

{

cout << "Base2::fun1()" << endl;

}

public:

int _b2;

};

class Derive :public Base1, public Base2

{

public:

virtual void fun1()

{

cout << "Derive::fun1()" << endl;

}

virtual void fun2()

{


}

public:

int _d;

};

各种继承内存布局(虚表)_虚继承虚表_03