아카이빙/C, C++

상속에서 객체의 생성, 소멸과정

셩님 2018. 5. 27. 04:14

상속과 객체의 생성, 소멸과정

샘플 코드를 만들어 실험을 해보자.


Base 클래스와 Derived 클래스 정의

class Base {
private:
int val;
public:
Base(int n) : val(n) {
cout << "Base(int)" << endl;
}
Base() {
cout << "Base()" << endl;
}
~Base() {
cout << "~Base()" << endl;
}
};

class Derived : public Base {
private:
int derivedVal;
public:
Derived(int n) : derivedVal(n) {
cout << "Derived(int)" << endl;
}
Derived() {
cout << "Derived()" << endl;
}
~Derived() {
cout << "~Derived()" << endl;
}
};


Case 1

Derived d(5);

Base()
Derived(int)
~Derived()
~Base()
  • Derived 클래스가 생성될 때는 Base 클래스의 생성자가 먼저 호출된다.

  • 소멸은 생성 순서의 반대

  • Base(int) 생성자를 활용하지 않으면 default는 Base() 생성자가 호출된다.


Case 2

Base* d = new Derived(5);
delete d;

Base()
Derived(int)
~Base()
  • Derived 포인터의 반환을 Base 포인터에 담을 경우

  • Derived 생성자는 호출되지만, 소멸자는 호출되지 않는다.

  • Derived 생성자가 호출되면서 Based 생성자가 먼저 호출 됨.


'아카이빙 > C, C++' 카테고리의 다른 글

가상함수(Virtual function)의 동작원리  (0) 2018.05.27
malloc과 new의 차이  (0) 2018.05.27
struct와 class 차이  (0) 2018.05.27
strcpy와 strncpy  (0) 2018.05.27
string과 character 배열  (0) 2018.05.26