Menu
Coddy logo textTech

생성자 및 소멸자 기초

Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 104개 중 10번째.

생성자는 객체가 생성될 때 자동으로 실행되는 특별한 메서드입니다. 소멸자는 객체가 destroyed될 때 실행됩니다.

Default constructor

class Book {
private:
    std::string title;
    int pages;

public:
    Book() {
        this->title = "Unknown";
        this->pages = 0;
    }
};

매개변수가 있는 constructor

Book(std::string title, int pages) {
    this->title = title;
    this->pages = pages;
}

생성자 오버로딩: 여러 생성자

class Book {
private:
    std::string title;
    int pages;

public:
    Book() {
        this->title = "Unknown";
        this->pages = 0;
    }
    
    Book(std::string title) {
        this->title = title;
        this->pages = 0;
    }
    
    Book(std::string title, int pages) {
        this->title = title;
        this->pages = pages;
    }
};

destructor: 객체가 destroyed될 때 실행

class Book {
public:
    ~Book() {
        std::cout << "Book destroyed" << std::endl;
    }
};

서로 다른 생성자를 사용하여 객체 만들기

Book book1;                        // 기본 생성자
Book book2("Harry Potter");         // 매개변수 하나
Book book3("1984", 328);            // 매개변수 두 개

생성자는 return 타입 없이 클래스와 동일한 이름을 사용합니다. 소멸자는 ~ClassName()을 사용하며, 객체가 스코프를 벗어나면 생성된 역순으로 자동 호출됩니다.

challenge icon

챌린지

중급

세 개의 오버로드된 생성자와 소멸자를 가진 Product 클래스를 생성하세요:

  • 3-parameter 생성자: name, price, stock
  • 2-parameter 생성자: name, price (stock = 0)
  • Default 생성자: name = "Unknown", price = 0, stock = 0
  • 소멸자: "Destroying: <name>"을 출력합니다

직접 해보기

#include <iostream>
#include "Product.h"

int main() {
    std::string name;
    int price, stock;
    std::getline(std::cin, name);
    std::cin >> price >> stock;
    
    Product product1(name, price, stock);
    Product product2("Keyboard", 79);
    Product product3;
    
    std::cout << "Product 1: " << product1.getName() << " - $" << product1.getPrice() << " (Stock: " << product1.getStock() << ")" << std::endl;
    std::cout << "Product 2: " << product2.getName() << " - $" << product2.getPrice() << " (Stock: " << product2.getStock() << ")" << std::endl;
    std::cout << "Product 3: " << product3.getName() << " - $" << product3.getPrice() << " (Stock: " << product3.getStock() << ")" << std::endl;
    return 0;
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러