首页 > 代码库 > C++ Primer Plus学习笔记之继承类的初始化顺序

C++ Primer Plus学习笔记之继承类的初始化顺序

C++ Primer Plus学习笔记之继承类的初始化顺序

基类的构造函数,析构函数和操作符函数operator=是不能被派生类继承的;
那么,当创建一个派生类对象时,怎样调用基类的构造函数对基类的数据进行初始化呢???
答案是:构造函数执行时遵行先兄长(基类),再客人(对象成员),后自己(派生类)的顺序;
另一方面,执行析构函数时,先执行派生类的析构函数,再执行基类的析构函数。原因是,对基类的破坏隐含了对派生类的破坏,所以派生类的析构函数必须先执行;
#include<iostream>

using namespace std;

class Member
{
	public:
		Member()
		{
			cout<<"Member created"<<endl;
		}
		~Member()
		{
			cout<<"Member destroyed"<<endl;
		}
};

class Base
{
	public:
		Base()
		{
			cout<<"Base created"<<endl;
		}
		~Base()
		{
			cout<<"Base destroyed"<<endl;
		}
};

class Derived:public Base
{
	public:
		Derived()
		{
			cout<<"Derived created"<<endl;
		}
		~Derived()
		{
			cout<<"Derived destroyed"<<endl;
		}
	private:
		Member m;
};

int main(int argc,char *argv[])
{
	Derived d;

	return 0;
}
运行结果:

Base created

Member created

Derived created

Derived destroyed

Member destroyed

Base destroyed