[C++ 객체지향] 생성자 초기화 리스트

초기화 리스트는 쉽게 말해서 클래스를 만들 때 초기화를 시켜주는 과정에서 this를 사용해서 하지 않고 리스트를 통해 초기화 시키는 걸 말함.

#include <iostream>

class A
{
    private:
        int a;
    public:
        A(int a) : a(a)
        {

        }
        int getA()
        {
            return a;
        }
};

int main()
{
    A *tmp = new A(2);
    std::cout << tmp->getA() << std::endl;
    delete tmp;
}

 

변수 명이 다르게 들어오는 걸 보여주기 위해서 밑 코드를 작성함.

#include <iostream>

class A
{
    private:
        int a;
    public:
        A(int b) : a(b)
        {

        }
        int getA()
        {
            return a;
        }
};

int main()
{
    A *tmp = new A(2);
    std::cout << tmp->getA() << std::endl;
    delete tmp;
}