Qaupot Blog
Software Engineering, Trip

404. 오버라이드 (Override)

🕐 Thu, 13 Mar 2014 09:00:00 GMT

오버라이딩 (오버라이드, 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();
    }
};
이 블로그는 개인 블로그입니다. 게시글은 오류를 포함하고 있을 수 있지만, 저자는 오류를 해결하기 위해 노력하고 있습니다.
게시글에 별도의 고지가 없는 경우, 크리에이티브 커먼즈 저작자표시-비영리-변경금지 4.0 라이선스를 따릅니다.

This blog is personal blog. published posts may contain some errors, but author doing efforts to clear errors.
If post have not notice of license, it under creative commons Attribution-NonCommercial-NoDerivatives 4.0.