부모 클래스에서 미리 구현된 내용을 상속받아 자식클래스에서 확장한다. 또한 부모 자식관계의 클래스에서 형변환은 기본적으로 ‘자식에 부모를 담지못한다’, ‘부모에 자식은 담을 수 있다’를 유념한다.
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 | class MyClassParent { public : MyClassParent(); MyClassParent( int x, int y) { this ->width = x; this ->height = y; } protected : int width; int height; private : // Error - private로 선언시 상속받은 클래스에서 접근할 수 없다. // => protected 에 선언한다. //int width; //int height; }; // 다음과 같은 형태로 상속 받는다. class MyClass : public MyClassParent { public : MyClass(); int getArea() { return this ->width * this ->height; } int initArea; }; // 다음과 같은 형태로 부모클래스의 생성자를 호출할 수 있다. MyClass::MyClass():MyClassParent(100, 20) { this ->initArea = this ->width * this ->height; } // - END header int _tmain( int argc, _TCHAR* argv[]) { // 상속의 예 MyClass initClass; cout << initClass.initArea; // 1>> 형변환 // [Error] 자식클래스에 부모객체는 담지 못한다. MyClassParent parentClass1; /*MyClass childClass1 = parentClass1;*/ // [OK] 부모클래스에 자식객체는 담을 수 있다. MyClass childClass2; MyClassParent parentClass2 = childClass2; // 2>> 포인터간 형변환 // [ERROR] 자식클래스의 포인터에 부모객체의 주소는 담지 못한다. MyClassParent parentClassPointer1; /*MyClass* childClassPointer1 = &parentClassPointer1;*/ // [OK] 부모클래스의 포인터에 자식객체의 주소는 담을 수 있다. MyClass childClassPointer2; MyClassParent* parentClassPointer2 = &childClassPointer2; // 레퍼런스간 형변환 // [ERROR] 자식클래스의 참조값에 부모객체의 주소는 담지 못한다. MyClassParent parentClassReference1; /*MyClass childClassReference1 = &parentClassReference1;*/ // [OK] 부모클래스의 참조값에 자식객체의 주소는 담을 수 있다. MyClass childClassReference2; MyClassParent& parentClassReference1 = childClassReference2; return 0; } |
* 자식클래스에서는 부모클래스의 public: & protected: 에만 접근이 가능하다. * 부모클래스에 자식객체는 담을 수 있다. 반대로는 불가하다. * 부모클래스의 포인터에 자식객체의 주소는 담을 수 있다. 반대로는 불가하다. * 부모클래스의 참조값에 자식객체의 주소는 담을 수 있다. 반대로는 불가하다.