C++ 생성자 초기화 리스트: 왜 쓰고 어떻게 쓰는가
객체 인스턴스화 시 생성자는 멤버 변수 초기화를 담당합니다. 이때 생성자 초기화 리스트(Initialization List)는 생성자 본문이 실행되기 전에 멤버 변수를 직접 초기화하는 간결하고 효율적인 방법을 제공합니다. 성능상 이점 외에도 const 변수나 기반 클래스 멤버 때문에 필수적인 경우도 있습니다.
생성자 초기화 리스트란?
생성자 초기화 리스트는 멤버 변수를 직접 초기화하는 절차로, 기본 생성자가 호출된 후 대입하는 방식이 아닙니다.
문법
ClassName(type1 param1, type2 param2) : member1(param1), member2(param2) {
// 생성자 본문
}
여기서 member1, member2는 생성자 본문 실행 전 param1, param2로 초기화됩니다.
초기화 리스트 예제
#include <iostream>
#include <string>
class Student {
public:
Student(const std::string& name, int age) : name(name), age(age) {}
void display() const {
std::cout << "Name: " << name << ", Age: " << age << "\n";
}
private:
std::string name;
int age;
};
int main() {
Student s("Navya", 20);
s.display();
return 0;
}
출력
Name: Navya, Age: 20
왜 생성자 초기화 리스트를 쓰는가?
- 기본 초기화 후 재대입을 피하여 시간과 자원 절약
- const 변수, 참조 멤버, 기반 클래스 멤버에는 필수적
- 모든 초기화 로직을 생성자 본문과 분리해 한 곳에 모음
특수한 경우들
Const 또는 참조 멤버
const 변수와 참조 멤버는 재대입할 수 없으므로 초기화 리스트에서 반드시 초기화해야 합니다.
class Config {
public:
Config(const std::string& product, const int& model) : product(product), model(model) {}
private:
const std::string product;
const int& model;
};
기반 클래스 초기화
파생 클래스가 기반 클래스를 상속받을 때, 초기화 리스트로 기반 클래스 생성자를 호출할 수 있습니다.
class Base {
public:
Base(int value) : baseValue(value) {}
protected:
int baseValue;
};
class Derived : public Base {
public:
Derived(int value, int extra) : Base(value), extraValue(extra) {}
private:
int extraValue;
};