C++

생성자와 멤버 초기화 리스트

Vetenir 2025. 1. 16. 20:54

생성자

객체가 생성된 직후에 자동으로 호출되는 함수.

  • 생성자에서 속성을 초기화하는 등 객체를 사용할 준비를 할 수 있습니다.
#include <iostream>

using namespace std;

template <typename T> // 템플릿 선언 추가
class SimpleVector {
public:
    SimpleVector() { // 생성자
        currentSize = 0;
        currentCapacity = 10;
        data = new T[currentCapacity];
    }

    ~SimpleVector() { // 소멸자 추가 (동적 메모리 해제)
        delete[] data;
    }

private:
    int currentSize;     // 현재 요소 개수
    int currentCapacity; // 벡터의 용량
    T* data;             // 동적 배열
};

 

멤버 초기화 리스트

 

#include <iostream>

using namespace std;

template <typename T> // 템플릿 선언
class SimpleVector {
public:
    // 생성자: 멤버 초기화 리스트 사용
    SimpleVector() 
        : currentSize(0), currentCapacity(10), data(new T[currentCapacity]) {}

    // 소멸자: 동적 메모리 해제
    ~SimpleVector() {
        delete[] data;
    }

private:
    int currentSize;     // 현재 요소 개수
    int currentCapacity; // 벡터의 용량
    T* data;             // 동적 배열
};

 

 

비교

SimpleVector() { // 생성자
	currentSize = 0;
	currentCapacity = 10;
	data = new T[currentCapacity];
}

SimpleVector() : currentSize(0), currentCapacity(10) { // 멤버 초기화 리스트로 표현한 생성자
    data = new T[currentCapacity];
}

 

두 코드의 역할은 동일합니다.