유도된 클래스들의 생성과 초기화

부모클래스를 상속한 자식클래스의 크기를 보게되면
부모클래스의 크기까지 포함된걸 볼 수 있다.
sizeof로 확인한다. 패딩으로인해 정확한 사이즈는 안나온다.

다중상속을 하게됬을때 A > B > C 로 상속하게되면 C는 A의 생성자를 실행하지 못한다.

생성자는 부모부터 소멸자는 자식부터 실행된다. 잊지말자!

 

#include <iostream>

using namespace std;

class A
{
private:
	int m_i;

public:
	A(const int &a) :m_i(a) {
		cout << "A Constructor" << endl;
	}

	~A() {
		cout << "A Destructor" << endl;
	}

};

class B : public A
{
public:
	double m_d;
	B(const int & i, const double &b)
		: A(i), m_d(b) {
		cout << "B Constructor" << endl;
	}
	~B() {
		cout << "B Destructor" << endl;
	}
};

class C : public B
{
public:
	char m_c;
	C(const int & i, const double &b,const char & c)
		: B(i,b), m_c(c) {
		cout << "C Constructor" << endl;
	}
	~C() {
		cout << "C Destructor" << endl;
	}
};


int main()
{

	cout << sizeof(A) << endl;
	cout << sizeof(B) << endl;
	cout << sizeof(C) << endl;

	C c(1, 1.3, 'a');

	return 0;
}

+ Recent posts