프로그래밍/C++

[C++] 초기화 리스트 (member initializer list)

갓똥 2019. 11. 5. 00:37
728x90
반응형

1. 멤버 초기화 리스트 (member initializer lists)

#include <iostream>

class Point {
    int x;
    int y;
public:
    Point(int a, int b) : x(a), y(b) { // 멤버 초기화 리스트
        // x = a;
        // y = b;
    }
};

int main() {
    Point p(1, 2);
    
    
    //--
    class a = 0; // 초기화. 생성자 호출
    
    class b;     // 생성자 호출
    b = 0;       // 대입. 대입연산자 호출
}

  ① 멤버 초기화 리스트란?

    => 생성자 괄호 ( ) 뒤에 콜론(:)을 표기하고 멤버를 초기화 하는 것


  ② 특징

    => 대입(assignment)이 아닌 초기화(initialization)

 


2. 반드시 멤버 초기화 리스트를 사용해야 하는 경우

#include <iostream>

class Point {
    const int conv;
    int& r;
    
public:
    Point(int a, int b) : conv(a), r(b) {
        // conv = a; - 대입으로 error
        // r = b;
    }
};

int main() {
    Point p(1, 2);
}

  ① 클래스 안에 멤버 데이터가 const 또는 reference로 되어 있을 때

 

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

class Rect {
    Point p1;
    Point p2;
public:
    Rect(int a, int b, int c, int d) : p1(a, b), p2(c, d) {}
};

int main() {
    Rect r; // p1 Point 생성자 -> p2 Point 생성자 -> Rect 생성자
}

 

  ② 클래스 안에 디폴트 생성자가 없는 타입이 멤버 데이터로 있을 때

 


3. 주의사항

#include <iostream>

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

int main() {
    Point p;
    
    std::cout << p.x << std::endl; // 0?
}
x
y

  - 클래스 내부에서 x, y순으로 선언을 했기 때문에 메모리에 위와 같이 x가 앞에 오게 된다.

  - 멤버 초기화 리스트를 사용할 시 대입이 아닌 초기화기 때문에 선언된 순(메모리 순)으로 먼저 초기화 된다.

  - 따라서 위의 경우는 멤버 초기화 리스트 사용시 x가 먼저 초기화 된다. (x에는 쓰레기 값이 들어간다)

 

  ① 초기화 순서

    => 초기화 리스트의 순서대로 초기화 되지 않는다.

    => 멤버 데이터가 놓인 순서대로 초기화 된다.

 


4. 멤버 데이터를 초기화하는 3가지 방법

#include <ioostream>

class Point {
    int x = 0; // C++11 이상
    int y = 0;
public:
    Point(int a, int b) : x(a), y(b) {
        x = a;
        y = b;
    }
};

int main() {
    Point p(1, 2);
}

  ① member field initialization

    => 생성자로 전달된 값을 사용할 수 없다.


  ② member initializer list

    => 가장 널리 사용되는 방법

    => 대입이 아닌 초기화

 

  ③ 생성자 블록 안에서 초기화

    => 초기화가 아닌 대입

 

  - 클래스를 선언과 구현으로 분리 하는 경우

    => 초기화 리스트는 구현부에 작성한다.

728x90
반응형