继承的构造与析构

子类对象在构造时,先调用父类的构造函数,然后再调用自己的构造函数,析构顺序相反。

看下测试代码:

#include <cstdlib>
#include <iostream>

using namespace std;

class grandparent
{
public:
	grandparent()
	{
		cout<<"grandparent()"<<endl;
	}
	~grandparent()
	{
		cout<<"~grandparent()"<<endl;
	}
};
class Parent : public grandparent
{
public:
	Parent()
	{
		cout<<"Parent()"<<endl;
	}

	~Parent()
	{
		cout<<"~Parent()"<<endl;
	}
};

class Child : public Parent
{
public:
	Child()
	{
		cout<<"Child()"<<endl;
	}

	~Child()
	{
		cout<<"~Child()"<<endl;
	}
};

void run()
{
	Child child;
}

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

	cin.get();
	return 0;
}


输出结果如下:

结果很明显了,子类构造时,先调用父亲的构造函数,父亲发现他还有父亲,于是父类就去调用子类的爷爷,

调用结束后继续父类的构造,父类构造结束后才调用子类的构造函数,析构时顺序相反~~

更多内容请查看深度探索C++对象模型

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值