C++类继承--构造函数时先构造基类

以下说明继承类函数构造时,先构造基类;

析构基类时,若没加上virtual,只析构基类,不析构派生类;

析构派生类时,同时会析构基类;

1. 基类析构函数有virtual

#include <stdio.h>

class Base
{
public:
	int a;
	Base(){
		a=0;
		printf("base construct\n");
	}
	virtual ~Base(){
		printf("base delete\n");
	}

	
	virtual void setA()=0;
	
};

class A:public Base
{
public:
	A(){
		a = 10;
		printf("A construct\n");
	}
	~A(){
		printf("A class delete\n");
	}
	virtual void setA()
	{
		a = 2;
	}
};

int main()
{
	
	Base *x = new A();
	A *aClass = new A();
	
	delete x;
	printf("---------------\n");
	delete aClass;
	
	return 0;
}

运行结果:

2. 基类析构函数无virtual

class Base
{
public:
	int a;
	Base(){
		a=0;
		printf("base construct\n");
	}
	~Base(){
		printf("base delete\n");
	}
	virtual void setA()=0;
};

  运行结果为:

 

  

 

posted on 2018-05-24 18:03  Anlia  阅读(1151)  评论(0编辑  收藏  举报

导航