오버라이딩 (오버라이드, Override)
부모의 메소드를 파생 클래스에서 재정의 하는 일을 오버라이딩이라고 합니다.
#include <iostream>
class Person
{
public:
void Method()
{
std::cout << "Person's Method" << std::endl;
}
};
class Student : public Person
{
public:
void Method()
{
std::cout << "Student's Method" << std::endl;
}
};
class Employee : public Person
{
public:
void Method()
{
std::cout << "Employee's Method" << std::endl;
}
};
int main(int argc, char** argv)
{
Person* person = new Person;
Student* student = new Student;
Employee* employee = new Employee;
person->Method();
student->Method();
employee->Method();
std::cout << std::endl;
((Person*)student)->Method();
((Person*)employee)->Method();
std::cout << std::endl;
delete person;
delete student;
delete employee;
}
Person's Method
Student's Method
Employee's Method
Person's Method
Person's Method
위의 예제에서 void 반환형을 가지고 어떠한 인수도 받지 않는 동일한 규격의
Method라는 함수를 각 클래스별로 만들었습니다.
만약 인수가 다를경우 이는 오버라이딩이 아니라 오버로딩이 됩니다.
이 함수를 각 인스턴스에서 호출했을 때, 결과는 해당 자료형의 메소드가 호출 됩니다.
그리고, 각 인스턴스의 포인터를 부모의 포인터로 캐스팅 하고 해당 메소드를 호출하면
캐스팅 된 이후의 자료형의 메소드가 호출됩니다.
위의 경우는 Student와 Employee를 Person으로 캐스팅 했고,
Method를 호출했을 때 Person의 Method가 호출되었습니다.
오버 라이드는 이후에 다룰 가상 함수에 의해
다형성(Polymorphism)을 지원하는 중요한 역할을 하게 되며,
가상함수를 지정하면 위의 예제와는 전혀 다른 결과가 나올 수 있게 됩니다.
(Student와 Employee를 Person으로 캐스팅 한 뒤,
Method를 호출했을 때 Student나 Employee의 Method가 호출될 수도 있습니다.)
오버라이드시 기존 함수의 호출
부모의 함수를 호출하고 싶다면,
함수의 호출시 Scope를 부모 클래스로 명시적 지정할 수 있습니다.
예를 들면, Employee 클래스의 코드를 아래와 같이 수정할 수 있습니다.
class Employee : public Person
{
public:
void Method()
{
Person::Method();
}
};