본문 바로가기

Programming/C++ 3

[C++] 08-03. 가상 소멸자

반응형

상.동.다

상속관계에서 생성자에서 동적할당을 할경우에 기초클래스의 멤버도 동적할당을 하기때문에 [다형성 특성]

모든 소멸자가 호출되기 위해서는 소멸자를 정의할 때 virtual로 선언.

#include <iostream>
using namespace std;

class First
{
private:
	char* strOne;
public:
	First(const char* str)
	{
		strOne = new char[strlen(str) + 1];
	}
	virtual ~First()
	{
		cout << "~First()" << endl;
		delete[]strOne; strOne = NULL;
	}
};

class Second:public First
{
private:
	char* strTwo;
public:
	Second(const char* str1,const char* str2):First(str1)
	{
		strTwo = new char[strlen(str2) + 1];
	}
	virtual ~Second()
	{
		cout << "~Second()" << endl;
		delete[]strTwo; strTwo = NULL;
	}
};

int main(void)
{
	First* ptr = new Second("simple", "complex");
	delete ptr;
	return 0;
}

 

소멸자를 가상으로 선언함으로써 각각의 생성자 내에서 할당한 메모리 공간을 효율적으로 해제할 수 있다.

-> 유도클래스의 소멸자가 호출이 되면서 기초클래스의 소멸자도 호출이 된다.

 


참조자의 참조 가능성

C++에서, AAA형 포인터 변수는 AAA객체 또는 AAA를 직접 혹은 간접적으로 상속하는 모든 객체를 가리킬 수 있다.

C++에서, AAA형 참조자는 AAA 객체 또는 AAA를 직접 혹은 간접적으로 상속하는 모든 객체를 참조할 수 있다.

#include <iostream>
using namespace std;

class First
{
public:
	void FirstFunc()
	{
		cout << "FristFunc()" << endl;
	}
	virtual void SimpleFunc()
	{
		cout << "First's SimpleFunc()" << endl;
	}
};

class Second:public First
{
public:
	void SecondFunc()
	{
		cout << "SecondFunc()" << endl;
	}
	virtual void SimpleFunc()
	{
		cout << "Second's SimpleFunc()" << endl;
	}
};

class Third:public Second
{
public:
	void ThirdFunc()
	{
		cout << "ThirdFunc()" << endl;
	}
	virtual void SimpleFunc()
	{
		cout << "Third's SimpleFunc()" << endl;
	}
};

int main(void)
{
	Third obj;
	obj.FirstFunc();
	obj.SecondFunc();
	obj.ThirdFunc();
	obj.SimpleFunc();

	Second& sref = obj;
	sref.FirstFunc();
	sref.SecondFunc();
	sref.SimpleFunc();

	First& fref = obj;
	fref.FirstFunc();
	fref.SimpleFunc();
	return 0;
}

 

 

반응형