멤버 생성 리스트

김대익·2022년 3월 1일
#include <iostream>
using namespace std;

class Cat {
public:
	Cat() {
    	cout << "constructor" << '\n';
    }
    ~Cat() {
    	cout << "destructor" << '\n';
    }
    void speak() {
    	cout << "meow" << '\n';
    }
private:
	int mAge;
}

int main() {
	Cat kitty;
    kitty.speak();
    return 0;
}


위 코드를 실행해보면 이 순서대로 실행된다.
객체가 생성자에 의해 생성되고 (constructor)
객체의 함수가 실행되고 (meow)
모든 요청이 끝나면 stack frame에서 내려간다 (destructor)


#include <iostream>
class Cat
{
public:	
	Cat() {
    	mAge = 1;
    };
	Cat(int age) {
    	mAge = age;
    };
private:
	int mAge;
};

class Zoo {
public:
	Zoo(int kittyAge) {
    	mKitty = Cat(kittyAge);
    };
private:
	Cat mKitty;
};

int main() {
	Zoo cppZoo(5);
	return 0;
}


위 코드를 실행하게 되면 mKitty = Cat(kittyAge);에서 임시 Cat 객체가 생성된다.
먼저 main함수가 실행되고 Zoo cppZoo(5);로 Zoo클래스의 객체가 생성되는데
이 때 private 객체 mKitty는 인수가 없으므로
Cat() constructor와 같고

Cat() {
    	mAge = 1;
};

로 mAge는 1이 된다.
이후

Zoo(int kittyAge) {
	mKitty = Cat(kittyAge);
};

가 실행되면서 임시 Cat객체가 생성되고

mkitty = ...에 의해 cppZoo에 복사되면서 mKitty의 mAge는 5가 된다.


이렇게 임시 object가 생기고 사라지는 것을 막는 것이
member init list이다
사용법은 생성자 뒤에 멤버 객체를 써주고 initialize해주고 싶은 object를 적으면 된다.
Zoo(int kittyAge):mKitty(Cat(kittyAge))

0개의 댓글