Language/C++

[C++] OOP(객체지향)의 특성 - 멤버변수 초기화

Return 2022. 6. 6. 16:18

Introduce

멤버 변수를 초기화하는 방법에 대해 알아봅니다. 변수 초기화를 하지 않으면 다음과 같이 변수에 가비지값이 들어갈 수 있습니다. 

#include <iostream>
using namespace std;

class Player
{
public:
    int _hp;
};

int main()
{
    Player p;
    cout << p._hp << endl;
    return 0;
}

===== 실행 결과 =====
4201019

멤버 변수의 초기화 방법

  • 생성자에서 초기화 
  • 초기화 리스트
  • C++ 11 문법 

생성자에서 초기화 

객체를 호출할때 생성자에 의해서 생성이된다는 것을 알 수 있었습니다. 이과정에서 멤버변수의 초기화까지 같이합니다. 

#include <iostream>
using namespace std;

class Player
{
public:
    Player()
    {
        _hp = 100;
    }

public:
    int _hp;
};

int main()
{
    Player p;
    cout << p._hp << endl;
    return 0;
}

===== 실행 결과 =====
100

초기화 리스트 

#include <iostream>
using namespace std;

class Player
{
public:
    Player() : _hp(100) {} // 초기화 리스트

public:
    int _hp;
};

int main()
{
    Player p;
    cout << p._hp << endl;
    return 0;
}

===== 실행 결과 =====
100

C++ 11

생성자에서 초기화하지 않고, 멤버변수를 선언하는 동시에 초기화합니다. 

#include <iostream>
using namespace std;

class Player
{

public:
    int _hp = 100;
};

int main()
{
    Player p;
    cout << p._hp << endl;
    return 0;
}

===== 실행 결과 =====
100