含有对象成员的派生类构造函数和析构函数的执行顺序

// 例4.8 含有对象成员的派生类构造函数和析构函数的执行顺序。
#include<iostream>
using namespace std;
class Base{     //声明基类Base
  public:
    Base(int i){  //基类的构造函数
      x = i;
      cout<<"Constructing base class \n";
    }
    ~Base(){      //基类的析构函数
      cout<<"Destructing base class \n";
    }
    void show(){
      cout<<"x="<<x<<endl;
    }
  private:
    int x;
};

class A{
	public:
		A(){
			cout<<"AAAAAAAAA"<<endl;
		}
		~A(){
			cout<<"destructing A class \n";
		}
}; 
 
class Derived:public Base{  //声明公有派生类Derived
	public:
	  Derived(int i):Base(i){ //派生类的构造函数,缀上要调用的基类构造函数和对象成员构造函数
	    cout<<"constucting derived class\n";
	  }
	  ~Derived(){  //派生类的析构函数
	    cout<<"destructing derived class \n";
	  }
	private:
	  A d;  //d为基类的对象,作为派生类的内嵌对象成员
};
 
int main(){
  Derived obj(5);
  obj.show();
  return 0;
}

构造函数调用顺序:

先调用基类构造函数、再调用对象成员所在类的构造函数、最后调用派生类构造函数 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值