객체들의 타입이 다르면 똑같은 메시지가 전달되더라도 서로 다른 동작을 하는 것
객체 지향 기법에서 하나의 코드로 다양한 타입의 객체를 처리하는 중요한 기술
class Shape {
protected:
int x, y;
public:
void setOrigin(int x, int y) {
this->x = x;
this->y = y;
}
void draw() {
cout << "Shape Draw";
}
};
class Rectangle : public Shape {
private:
int width, height;
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
void draw() {
cout << "Rectangle Draw"
}
};
class Circle : public Shape {
private:
int radius;
public:
void setRadius(int r) {
radius = r;
}
void draw() {
cout << "Circle Draw" << endl;
}
};
상향 형변환 : 자식 클래스 타입을 부모 클래스 타입으로 변환
하향 형변환 : 부모 클래스 타입을 자식 클래스 타입으로 변환
■ 상향 형변환
Shape *ps = new Rectangle();
ps->setOrigin(10, 10);
■ 하향 형변환
Rectangle *pr = (Rectangle *)ps;
pr->setWidth(100);
((Rectangle*)ps)->draw();
예제
int main() {
Shape *ps = new Rectangle(); // 상향 형변환
ps->setOrigin(10, 10);
ps->draw();
((Rectangle *)ps)->draw(); // 하향 형변환
}