부모 객체를 통해 자식 객체의 멤버를 호출하고 싶다면..
Employee* emp = (Employee*)&rgl;
cout << emp->PayCehck() << endl;
가상함수란 자식 클래스에서 오버라이딩 될 것으로 예상되는 멤버함수를 의미한다. 상수 관계에서 부모 클래스와 자식 클래스 모두 같은 이름의 멤버 함수가 존재하되, 자식 클래스의 멤버함수를 재정의 할 수 있었다.
상속성의 문제점은 부모 클래스의 객체를 통해 자식 클래스에서 오버라이딩
해답은 virtual
class Parent {
virtual double PayCheck() {return 0.0;}
}
class descendant {
double PayCheck() {}
}
emp -> PayCheck()
⇒ 결과 값은 객체마다 달라진다. 여러 객체가 있을 때 오버라이딩된 함수를 통해 결과값을 출력하도록 작성할 수 있다. 즉 객체값만으로 결과를 출력할 수 있다.부서 만들기
1 step
class Department {
private:
Employee* emp[10];
};
2 step
class Department {
private:
Employee* employee[10];
int count;
public:
Department() { count = 0; }
void AddEmployee(Employee& emp) {
this->employee[count] = &&emp;
count++;
}
void Display() const {
for (int i = 0; i < count; i++) {
cout << "급여" << employee[i]->PayCehck() << endl;
}
}
};
// main
Department dept;
dept.AddEmployee(rgl);
dept.AddEmployee(tmp);
dept.AddEmployee(slm);
Employee* emp = (Employee*)&rgl;
cout << emp->PayCehck() << endl;
정적/동적 바인딩
처음부터 객체가 정해진 형태 ⇒ 정적바인딩
들어오는 객체에 따라 달라지는 형태 ⇒ 동적 바인딩
->
PayCheck() 호출 시 Regular, Temporary, SalesMan 클래스 객체에 따라 다른 급여액을 보여줄 것이다.virtual
가상 함수 존재해야하지만 기능으로써는 필요가 없을 때는 0을 대입하면 된다.virtual double PayCheck() = 0;
📚 reference
- C++ 프로그래밍과 STL(이창현)
- Photo by Hillshire Farm on Unsplash