본문 바로가기
개발/C++ (98,03,11,14,17,20,23)

Classic C++ : 생성자(constructor)와 소멸자(destructor)

by snowoods 2025. 11. 2.

Classic C++

 

constructor and destructor

 

개요

C++에서 객체가 생성될 때와 소멸될 때 자동으로 호출되는 특별한 멤버 함수인 생성자(Constructor)와 소멸자(Destructor)에 대해 알아봅니다.

 

C++ 버전별 주요 키워드 도입 시기

  • C++98 이전 (C++ with Classes): 생성자와 소멸자는 C++의 초기 버전부터 클래스의 핵심 기능으로 포함되었습니다.

 

내용 설명

  • 생성자란? 객체가 생성될 때 자동으로 실행되는 함수입니다.
  • 소멸자란? 객체가 소멸될 때 자동으로 실행되는 함수입니다.

 

예제 코드

#include <iostream.h>
#include <conio.h>

class Base
{

public:

    Base(){     // Constructor
        cout << "I am the constructor" << endl;
    }

    ~Base(){    // Destructor
        cout << "I am the destructor" << endl;
    }

};

void main()
{
    cout << "Starting main() function" << endl << endl;

    Base *B1 = new Base();
    Base *B2 = new Base();
    Base *B3 = new Base();

    cout << endl;

    delete B1;
    delete B2;
    delete B3;

    cout << endl << "Ending main() function" << endl;

    getch();

}

 

실행 결과

Starting main() function

I am the constructor
I am the constructor
I am the constructor

I am the destructor
I am the destructor
I am the destructor

Ending main() function

 

활용팁

  • 생성자는 주로 멤버 변수를 초기화하는 데 사용됩니다.
  • 소멸자는 동적으로 할당된 메모리를 해제하거나 파일 핸들을 닫는 등 객체가 사용한 자원을 정리하는 데 사용됩니다.
  • 클래스에 생성자나 소멸자를 명시적으로 정의하지 않으면 컴파일러가 기본 버전을 자동으로 생성합니다.