가상 소멸자
C++에서는 가상 함수(virtual)가 하나라도 있는 클래스라면
소멸자도 virtual로 만드는 것이 안전한 습관이다.
[예제]
부모-자식 객체 생성자/소멸자 순서
#include <iostream>
using namespace std;
class Base
{
public:
Base() { cout << "Base()" << endl; }
virtual ~Base() { cout << "~Base()" << endl; }
};
class Derived : public Base
{
public:
Derived() { cout << "Derived()" << endl; }
virtual ~Derived() { cout << "~Derived()" << endl; }
};
int main()
{
Derived d;
}
부모 객체 생성 → 자식 객체 생성
자식 객체 소멸 → 부모 객체 소멸
[예제] 가상 소멸자 필요성
#include <iostream>
using namespace std;
class Base
{
public:
Base() { cout << "Base()" << endl; }
~Base() { cout << "~Base()" << endl; }
};
class Derived : public Base
{
public:
Derived() { cout << "Derived()" << endl; }
~Derived() { cout << "~Derived()" << endl; }
};
int main()
{
Base* p = new Derived; // Derived 객체 생성
delete p; // ??? -> ~Base 소멸자만 호출됨 (메모리 누수 발생 가능)
}
자식 객체 소멸자가 호출되지 않았다!
만약 기반 클래스의 소멸자가 virtual이 아니면
기반 클래스 포인터로 파생 클래스 객체를 삭제할 때
p 타입이 Base* 이므로 Base 소멸자만 호출
이렇게 되면 파생 클래스에서 할당한 동적 메모리가 해제되지 않아
메모리 누수(memory leak) 가 발생할 수 있다.
→ 소멸자 호출 시 포인터 타입이 아닌 실제 가리키는 메모리 조사 필요
→ 기반 클래스 소멸자를 가상함수로 한다.
즉, 기반의 소멸자함수가 가상함수면 파생의 소멸자함수도 가상함수
[예제] 가상 소멸자
#include <iostream>
using namespace std;
class Base
{
public:
Base() { cout << "Base()" << endl; }
virtual ~Base() { cout << "~Base()" << endl; }
};
class Derived : public Base
{
public:
Derived() { cout << "Derived()" << endl; }
virtual ~Derived() { cout << "~Derived()" << endl; }
};
int main()
{
Base* p = new Derived; // Derived 객체 생성
delete p;
}
상속에서 기반클래스 소멸자는 virtual 함수 사용하는 것이 좋다.
* 의도적으로 가상함수로 두지 않는 경우도 있다.
📌 [C++] 가상 함수 (virtual funciton)
[C++] 가상 함수 (virtual funciton)
가상 멤버 함수 (virtual function)동적 바인딩을 위해 사용class A{public: virtual void sub(void);}; [예제] 함수 재정의(overriding) 주의사항#include class Animal{public: void Cry() { std::cout Cry(); // ??? -> Dog? Animal?}Q) p-
zoosso.tistory.com
'프로그래밍 언어 > C++' 카테고리의 다른 글
[C++] 함수 바인딩 (Funciton Binding) (3) | 2025.02.22 |
---|---|
[C++] mutable 키워드 (1) | 2025.02.21 |
[C++] 상수 멤버함수 const member function (5) | 2025.02.19 |
[C++] return by reference (4) | 2025.02.15 |
[C++] class this 키워드 (8) | 2025.02.08 |
댓글