1 class base_class{ 2 public: 3 base_class(){ 4 cout<<"base_class constructor called "; 5 } 6 ~base_class(){cout<<"base_class destructor called "; //虚函数 将调用派生类的析构函数 再调用基类的析构函数 7 } 8 }; 9 class derived_class:public base_class{ 10 public: 11 derived_class(){ 12 cout<<"derived_class constructor called "; 13 } 14 ~derived_class(){ 15 cout<<"derived_class destructor called "; 16 } 17 }; 18 void main(){ 19 derived_class *sample_ptr=new derived_class; //当创建一个派生类变量时,先调用基类的构造函数,再调用派生类的构造函数 20 system("pause"); 21 }
运行:
当新建一个派生类变量时,首先调用基类的构造函数,然后调用派生类的构造函数
删除该变量,调用析构函数,首先调用派生类的析构函数,然后调用基类的析构函数
1 void main(){ 2 derived_class *sample_ptr=new derived_class; //当创建一个派生类变量时,先调用基类的构造函数,再调用派生类的构造函数 3 delete sample_ptr; 4 sample_ptr=NULL; //删除变量后,调用析构函数,首先调用派生类的析构函数,然后调用基类的析构函数 5 system("pause"); 6 }