CH08 상속

jiyoon·2024년 6월 12일
post-thumbnail

1. C++ 객체 지향 상속의 개념

  • 상속의 정의: 클래스 사이에서 상속 관계를 정의하여 기본 클래스의 속성과 기능을 파생 클래스에 물려주는 것.
  • 기본 클래스(Base Class): 상속해주는 클래스, 부모 클래스.
  • 파생 클래스(Derived Class): 상속받는 클래스, 자식 클래스.
  • 상속의 목적: 클래스 재사용, 확장, 계층적 분류, 코드 간결화.

1) 상속의 표현

  • 상속 선언: class 파생클래스명 : 접근지정자 기본클래스명 { ... };

    class Student : public Person { ... };
    class StudentWorker : public Student { ... };
  • 다중 상속: 다중 상속 시 기본 클래스의 멤버가 중복 상속될 수 있음.

    		class BaseIO {		// 기본 클래스 정의
    		};
    
    		class In : virtual public BaseIO {	// In 클래스는 BaseIO 클래스를 가상 상속함
    		};
    
    		class Out : virtual public BaseIO {	// Out 클래스는 BaseIO 클래스를 가상 상속함
    		};

2) 예제 8-1: Point 클래스를 상속받는 ColorPoint 클래스

상속의 특징

  • 파생 클래스의 객체는 기본 클래스의 멤버를 포함함
  • 파생 클래스 객체를 통해 기본 클래스의 public 멤버와 파생 클래스의 멤버에 접근 가능.
#include <iostream>
#include <string>
using namespace std;

class Point {
    int x, y;
public:
    void set(int x, int y) { this->x = x; this->y = y; }
    void showPoint() { cout << "(" << x << ", " << y << ")" << endl; }
};

class ColorPoint : public Point {
    string color;
public:
    void setColor(string color) { this->color = color; }
    void showColorPoint() {
        cout << color << ":";
        showPoint();		// 기본 클래스의 showPoint() 호출
    }
};

int main() {
    ColorPoint cp; 		// 파생 클래스 객체 생성
    cp.set(3, 4); 		// 기본 클래스의 멤버 함수 호출
    cp.setColor("Red"); // 파생 클래스의 멤버 함수 호출
    cp.showColorPoint(); // 파생 클래스의 멤버 함수 호출
    return 0;
}



2. 상속과 객체 포인터

1) 업 캐스팅 (Up-Casting)과 다운 캐스팅 (Down-Casting)

  • 업 캐스팅 : 파생 클래스 포인터가 기본 클래스 포인터로 치환되는 것.
  • 다운 캐스팅 : 기본 클래스 포인터가 파생 클래스 포인터로 치환되는 것.
  int main() {
      ColorPoint cp;
      Point* pBase = &cp; // 업 캐스팅
      pBase->set(3, 4);
      pBase->showPoint();
      pBase->showColorPoint();	//컴파일 오류. 기본 클래스만 접근 가능.
      
      ColorPoint *pDer;
      pDer = (ColorPoint *)pBase;	//다운캐스팅
      pDer -> setColorPoint();		//정상 컴파일
  }

3) protected 접근 지정

  • private 멤버: 선언된 클래스 내에서만 접근 가능.
  • public 멤버: 선언된 클래스 및 모든 외부 클래스에서 접근 가능.
  • protected 멤버: 선언된 클래스 및 파생 클래스에서 접근 가능.

상속 시 접근 지정에 따른 멤버 접근 속성 변화

  • public 상속: 기본 클래스의 protected, public 멤버를 그대로 계승.
  • protected 상속: 기본 클래스의 protected, public 멤버를 protected로 계승.
  • private 상속: 기본 클래스의 protected, public 멤버를 private으로 계승.
class Point {
protected:
    int x, y;
public:
    void set(int x, int y) { this->x = x; this->y = y; }
    void showPoint() { cout << "(" << x << ", " << y << ")" << endl; }
};

class ColorPoint : public Point {
    string color;
public:
    void setColor(string color) { this->color = color; }
    void showColorPoint() {
        cout << color << ":";
        showPoint();
    }
};

int main() {
    ColorPoint cp;
    cp.set(3, 4);
    cp.setColor("Red");
    cp.showColorPoint();
    return 0;
}



3. 상속 관계의 생성자와 소멸자 실행

1) 생성자 호출 관계 및 실행 순서

  • 파생 클래스의 객체 생성 : 기본 클래스의 생성자 -> 파생 클래스의 생성자
  • 파생 클래스의 객체 소멸 : 파생 클래스의 소멸자 -> 기본 클래스의 소멸자


2) 파생 클래스의 생성자에서 명시적으로 기본 클래스의 생성자 선택

파생 클래스는 컴파일러에 의해 기본 클래스의 생성자를 자동으로 호출한다. 따라서 기본 클래스에 기본 생성자가 없으면 컴파일 오류가 발생한다. 또한, 매개변수를 가진 파생 클래스도 기본 클래스의 기본 생성자를 호출하려고 시도하므로, 기본 클래스의 초기화가 필요할 수 있다. 이를 해결하기 위해 파생 클래스 생성자에서 명시적으로 기본 클래스의 생성자를 호출해야 한다.


3) 예제 8-3: TV, WideTV, SmartTV 생성자 매개 변수 전달



4. 다중 상속

  • C++에서 클래스는 여러 개의 클래스로부터 상속받을 수 있음.
  • 다중 상속을 선언하는 방법:

profile
주니어 개발자

0개의 댓글