1 minute read

클래스 생성자와 소멸자

  1. 생성자와 소멸자란?

클래스의 이름이 같고 리턴 타입이 없는 메서드를 생성자라고 부릅니다.

생성자는 클래스의 객체를 생성할 때 자동으로 호출 됩니다.

생성자와 동일한 형태이지만 앞에 “~”(탈데)를 붙인 메서드를 소멸자라고 부릅니다.

소멸자는 객체가 제거가 될 때 자동으로 호출 됩니다.

  1. 생성자와 소멸자 확인해보기

간단한 예제 입니다. 참고로 생성자를 영어로 constructor라고 하고, 소멸자를 destructor라고 합니다.

아래 코드의 생성자와 소멸자에는 각각 메시지를 출력하도록 클래스를 만들었습니다.

그리고, myTestClass라는 스마트포인터를 만들었어요. 이 때 생성될때 생성자가 호출되겠군요!

스마트 포인터를 사용하면 main에 대한 코드블럭이 끝나면 자동으로 생성된 클래스가 삭제되기 때문에 이때 destructor가 호출 되겠네요.

스마트포인터이기 때문에 따로 delete를 할 필요가 없습니다.

#include <iostream>
#include <memory>

class TEST
{
  public:
    //constructor
    TEST(){
      std::cout << "This is constructor this method is called when class is created" << std::endl;
    }
    //destructor
    ~TEST(){
      std::cout << "This is destructor this method is called when class is deleted" << std::endl;
    }
    int m_age;
};

int main(){
  auto myTestClass = std::make_unique<TEST>();
  myTestClass->m_age = 10;
  std::cout << "m_age = " << myTestClass->m_age << std::endl;
}

예상되는 결과는 아래와 같습니다. 1) 객체가 생성될 때 생성자를 호출 되는 메시지 출력

2) 중간에 m_age 메시지 출력

3) 코드가 종료되면서 객체가 삭제될 때 소멸자를 호출하는 메시지 출력

결과를 한번 확인해보세요~!

실행 결과
This is constructor this method is called when class is created
m_age = 10
This is destructor this method is called when class is deleted
  1. 생성자로 데이터 멤버를 초기화 하기

생성자 초기화할 때 사용되는 방법 중 하나는 ctor 이니셜라이저를 사용하는 것 입니다.

생성자 이름 뒤에 콜론 (”:”) 을 붙여서 표현 합니다. 그 뒤에 초기화해줄 멤버변수의 값을 괄호 안에 입력해주면 됩니다.

멤버변수에 m_age와 m_name 이 있는 상태에서 age = 10, name = “codingsalad”로 초기화 하는 예제 입니다.

#include <iostream>
#include <memory>

class TEST
{
  public:
    //constructor
    TEST():
      m_age(10),
      m_name("codingsalad")
    {
      std::cout << "This is constructor this method is called when class is created" << std::endl;
    }
    //destructor
    ~TEST(){
      std::cout << "This is destructor this method is called when class is deleted" << std::endl;
    }
    int m_age;
    std::string m_name;
};

int main(){
  auto myTestClass = std::make_unique<TEST>();
  std::cout << "m_age = " << myTestClass->m_age << std::endl;
  std::cout << "m_name = " << myTestClass->m_name << std::endl;
}

실행 결과를 확인해보면, main에서 아무런 동작을 하지 않고 출력했을 때에 초기화한 값으로 생성된 것을 확인할 수 있습니다.

Updated: