프로그래밍 언어/C++

생성자와 멤버 변수의 초기화

· 코딩마이데이

클래스의 멤버 변수들은 자동으로 초기화되지 않기 때문에 생성자에서 초기화합니다.

멤버 변수 초기화에 대해 알아봅시다.

 

생성자 코드에서 멤버 변수 초기화

다음은 2개의 생성자가 각각 멤버 변수를 초기화하는 Point 클래스의 사례입니다.

class Point {
	int x, y;
public:
	Point();
	Point(int a, int b);
};
Point::Point() { x = 0; y = 0; }
Point::Point(int a, int b) { x = a; x = b; }

 

생성자 서두에 초기값으로 초기화

이 2개의 생성자는 다음과 같이 생성자의 코드의 구현부에 멤버 변수와 초깃값을 쌍으로 지정하고 이들을 콤마(,)로 나열하여 작성할 수 있습니다.

Point::Point() { x = 0; y = 0; } // 멤버 변수 x, y를  0으로 초기화
Point::Point(int a, int b) // 멤버 변수 x=a로, y=b로 초기화
	: x(a), y(b) { // 콜론(;) 이하 부분을 다음 줄에 써도 됨
}

 

또는 다음과 같이 맴버 변수를 초기화해도 됩니다.

Point::Point(int a)
	: x(a), y(0) { // 멤버 변수 x=a, y=0으로 초기화
}
Point::Point(int a)
	: x(100 + a), y(100) { // 멤버 변수 x=100+a, y=100으로 초기화
}

 

클래스 선언부에서 직접 초기화

멤버 변수는 다음과 같이 선언문에서 직접 초기화할 수 있습니다.

class Point {
	int x = 0, y = 0; // 클래스 선언부에서 x, y를 0으로 직접 초기화
	...
};

 

예제 3-5 멤버 변수 초기화와 위임 생성자 활용

#include <iostream>
using namespace std;

class Point {
	int x, y;
public:
	Point();
	Point(int a, int b);
	void show() { cout << "(" << x << ", " << y << ")" << endl; }
};

Point::Point() : Point(0, 0) { } // Point(int a, int b) 생성자 호출

Point::Point(int a, int b)
	: x(a), y(b) { }


int main() {
	Point origin;
	Point target(10, 20);
	origin.show();
	target.show();
}

 

실행 결과

(0, 0)
(10, 20)