프로그래밍/C++
C++ 문법 - 가상함수
게으른구름
2018. 2. 19. 00:10
< 가상함수 (Virtual Function) >
가상함수는 업캐스팅된 객체가 오버라이딩한 method를 제대로 찾지 못할 때 사용됩니다.
먼저 사용하지 않았을 때를 살펴봅시다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; class Parent { public: void test() { cout << "부모" << endl; } }; class Child : public Parent { public: void test() { // 오버라이딩 cout << "자식" << endl; } }; int main() { Child c; Parent *up = &c; // 업캐스팅 up->test(); } | cs |
위와 같이 업캐스팅된 Child class의 객체 c가 Parent class의 test method를 실행합니다.
만약 오버라이딩한 Child class의 test method를 실행하고 싶다면 가상함수를 사용해야 합니다.
사용법은 간단합니다.
가상함수로 만들고 싶은 method의 return 형식 앞에 virtual을 써주면 됩니다.
이때 부모 class의 method 앞에만 써주면 됩니다. 왜냐하면 자식 class의 오버라이딩 method는 자동으로 가상함수가 되기 때문입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; class 부모 { public: virtual void test() { cout << "부모" << endl; } }; class 자식 : public 부모 { public: void test() { // 오버라이딩 cout << "자식" << endl; } }; int main() { 자식 c; 부모 *up = &c; // 업캐스팅 up->test(); } | cs |
가상함수를 사용하면 위와 같이 원하던 결과가 출력됩니다.