본문 바로가기

강의자료/Class

004. 상속관계에서의 생성자와 소멸자


◈ 이 글은 강의를 위하여 제가 직접 작성한 내용입니다. 따라서 퍼가실 경우, 출처를 명확히 해주시기 바랍니다!!
◈ This ariticle was written by me for teaching. So if you want to copy this article, please clarify the source!!


[매우 중요!!] 아래 코드를 실행해보고 상속관계에 있어서 부모 클래스와 자식 클래스 간의 생성자와 소멸자의 호출 순서에 대해서 이해한다. 
/*
>> 생성자 호출 순서
1. 자식 클래스의 객체 생성 시 : 부모 클래스의 생성자 호출 -> 자식 클래스의 생성자 호출
2. 자식 클래스의 객체 소멸 시 : 자식 클래스의 소멸자 호출 -> 부모 클래스의 소멸자 호출
*/

#include 
#include 
using namespace std; 

class Mammal
{
public:
	Mammal();
	Mammal(int age);
	~Mammal();

	int GetAge() const { return itsAge; }
	void SetAge(int age) { itsAge = age; }
	int GetWeight() const { return itsWeight; }
	void SetWeight(int weight) { itsWeight = weight; }

	void Speak()const { cout << "Mammal sound!\n"; }
	void Sleep()const { cout << "shhh. I'm sleeping.\n"; }

	// 부모가 자식에게 private에 대한 접근을 허용한다.
	int GetSpeed() const { return itsSpeed; }
	void SetSpeed(int speed) { itsSpeed = speed; }

protected:
	int itsAge;
	int itsWeight;

private:
	int itsSpeed;
};

Mammal::Mammal(): itsAge(1), itsWeight(5)
{
	cout << "Mammal constructor...\n";
}
Mammal::Mammal(int age): itsAge(age), itsWeight(5)
{
	cout << "Mammal(int) constructor...\n";
}
Mammal::~Mammal()
{
	cout << "Mammal destructor...\n";
}

enum BREED { GOLDEN, CAIRN, DANDIE};
class Dog : public Mammal
{
public:
	Dog();
	Dog(int age);
	Dog(int age, int weight);
	Dog(int age, BREED breed);
	Dog(int age, int weight, BREED breed);
	~Dog();

	BREED GetBreed() const { return itsBreed; }
	void SetBreed(BREED breed) { itsBreed = breed; }

	void WagTail() const { cout << "Tail wagging...\n"; }
	void BegForFood() const 
	{ cout << "Begging for food...\n"; }

private:
	BREED itsBreed;
};

Dog::Dog(): Mammal(), itsBreed(GOLDEN)
{
	cout << "Dog constructor...\n";
}
Dog::Dog(int age): Mammal(age), itsBreed(GOLDEN)
{
	cout << "Dog(int) constructor...\n";
}
Dog::Dog(int age, int weight): Mammal(age), itsBreed(GOLDEN) //, itsWeight(weight) 는 작성불가.
{
	itsWeight = weight;
	cout << "Dog(int, int) constructor...\n";
}
Dog::Dog(int age, int weight, BREED breed): Mammal(age), itsBreed(breed)
{
	itsWeight = weight;
	cout << "Dog(int, int, BREED) constructor...\n";
}
Dog::Dog(int age, BREED breed): Mammal(age), itsBreed(breed)
{
	cout << "Dog(int, BREED) constructor...\n";
}
Dog::~Dog()
{
	cout << "Dog destructor(" << itsAge << ")...\n";
}

void main()
{
	Dog fido;
	cout << "---------------------------------" << endl;
	Dog rover(5);
	cout << "---------------------------------" << endl;
	Dog buster(6,8);
	cout << "---------------------------------" << endl;
	Dog yorkie(3,DANDIE);
	cout << "---------------------------------" << endl;
	Dog dobbie(4,20,CAIRN);
	cout << "---------------------------------" << endl;
	fido.Speak();
	rover.WagTail();
	cout << "---------------------------------" << endl;
	cout << "Yorkie is " << yorkie.GetAge() << " years old\n";
	cout << "Dobbie weighs " << dobbie.GetWeight() << " pounds\n";
	cout << "---------------------------------" << endl;
}