
상속 선언: 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 클래스를 가상 상속함
};

#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;
}

int main() {
ColorPoint cp;
Point* pBase = &cp; // 업 캐스팅
pBase->set(3, 4);
pBase->showPoint();
pBase->showColorPoint(); //컴파일 오류. 기본 클래스만 접근 가능.
ColorPoint *pDer;
pDer = (ColorPoint *)pBase; //다운캐스팅
pDer -> setColorPoint(); //정상 컴파일
}
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;
}

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


