1. 程式人生 > >C++ 虛基類建構函式的執行順序

C++ 虛基類建構函式的執行順序

(1)呼叫基類的建構函式,多個基類則按派生類宣告時

          列出的次序、從左到右呼叫,而不是初始化列表中

          的次序。

(2)呼叫物件成員(子物件)的建構函式,按類宣告中

          物件成員出現的次序呼叫,而不是初始化列表中的

          次序。

(3)執行派生類的建構函式。

同一層中對虛基類建構函式的呼叫總是先於普通基類的構

造函式。

#include<iostream>
using namespace std;

class A//基類A
{
public:
	A(){cout<<"class A"<<endl;}
};

class B: public A //由A類派生出類B
{
public:
	B(){cout<<"class B"<<endl;}
};

class C1:virtual public B //由類B虛擬派生出類C1
{
public:
	C1(){cout<<"class C1"<<endl;}
};

class C2:virtual public B //由類B虛擬派生出類C2
{
public:
	C2(){cout<<"class C2"<<endl;}
};

class D:public C1, public C2 //由C1和C2派生出類D
{
public:
	D(){cout<<"class D"<<endl;}
};

int main()
{
	D d;
	return 0;
}
#include<iostream>
using namespace std;

class M
{
public:
	M(const char *s){cout<<"M:"<<s<<endl;}
};

class A
{
	M m;
public:
	A(const char* s):m("in A"){cout<<"A:"<<s<<endl;}
};

class B
{
	M m;
public:
	B(const char* s):m("in B"){cout<<"B:"<<s<<endl;}
};

class C
{
	M m;
public:
	C(const char* s):m("in C"){cout<<"C:"<<s<<endl;}
};

class D
{
	M m;
public:
	D(const char* s):m("in D"){cout<<"D:"<<s<<endl;}
};


class E:public A, virtual public B, virtual public C
{
	M m;
public:
	E(const char* s):A("from E"),B("from E"),C("from E"),m("in E")
	{cout<<"E:"<<s<<endl;}
};

class F:virtual public B, virtual public C, public D
{
	M m;
public:
	F(const char* s):B("from F"),C("from F"),D("from F"),m("in F")
	{cout<<"F:"<<s<<endl;}
};

class G:public E, public F
{
	M m;
public:
	G(const char* s):B("from G"),C("from G"),E("from G"),F("from G"),m("in G")
	{cout<<"G:"<<s<<endl;}
};

int main()
{
	G g("from main");
	return 0;
}