[C++] 소멸자(Destructor), 디폴트 소멸자(Default destructor)

728x90
반응형

생성자는 객체가 "생성" 될 때 자동으로 호출되는 함수다. 이와 반대로 객체가 "소멸"될 때 자동으로 호출되는 함수가 바로 소멸자다.

#include <iostream>
#include <string.h>

class people {
    int height;
    int weight;
    char* name;

    public :
        people(int h, int w, const char* name_);
        ~people();

        void show(void);
};

people::people(int h, int w, const char* name_)
{
    std::cout<< "생성자 호출"<<std::endl;
    height = h;
    weight = w,

    name = new char(strlen(name_) + 1);
    strcpy(name, name_);
}

void people::show(void)
{
    std::cout << "height : "<< height <<std::endl;
    std::cout << "weight : "<< weight <<std::endl;
    std::cout << "name : "<< name <<std::endl;
}

people::~people()
{
    if(name) {
        std::cout << " 소멸자 호출 "<<std::endl;
        delete[] name;
    }
}

int main(void)
{
    people p1(175, 73, "Jhon");

    p1.show();
}

위 코드를 실행한 결과는 아래와 같다. 

생성자 호출
height : 175
weight : 73
name : Jhon
 소멸자 호출


소멸자는 객체가 소멸되는 시점에 호출되는 함수다. 소멸자는 매개변수가 없으며(즉, 오버로딩 되지 않는다.), 선언은 Class의 이름을 그대로 사용하며 앞에 "~"을 붙여준다. 

~People()

People::~People()
{
}

위와 같은 형태다. 소멸자또한 Default destructor가 있다.

728x90
반응형