단순히 자식 클래스 객체를 부모 클래스 객체로 취급하는 것

예제

class Shape {
	...
}
class Rectangle : public Shape {
	...
}
int main() {
	Shape *ps = new Rectangle();
	ps->draw();
}

→ 만약 Shape 포인터를 통해 멤버 변수를 호출해도 도형의 종류의 따라 서로 다른 draw()가 호출됨

→ 사각형일 땐 사각형을 그리는 draw(), 원일 땐 원을 그리는 draw()가 호출

즉, draw()를 가상 함수로 작성하면 가능하다.

#include <iostream>
#include <string>
using namespace std;

class Shape {
protected:
	int x, y;

public:
	void setOrigin(int x, int y) {
		this->x = x;
		this->y = y;
	}
	
	virtual void draw() {
		cout << "Shape Draw" << endl;
	}
};

class Rectangle : public Shape {
	void draw() {
		cout << "Rectangle Draw" << endl;
	}
};

int main() {
	Shape *ps = new Rectangle();
	ps->draw();
	delete ps;
	
	Shape *ps1 = new Circle();
	ps1->draw();
	delete ps1;
	return 0;
}

동적 바인딩

class Triangle: public Shape {
private:
	int base, height;
public:
	void draw() {
		cout << "Triangle Draw" << endl;
	}
};

int main() {
	Shape *arrayOfShapes[3];
	
	arrayOfShapes[0] = new Rectangle();
	arrayOfShapes[1] = new Triangle();
	arrayOfShapes[2] = new Circle();
	for (int i = 0; i < 3; i++) {
		arrayOfShapes[i]->draw();
	}
}

참조자와 가상함수