C++의 가상 함수는 파생 클래스 개체의 종류를 모른 채 기본 클래스 포인터 목록을 만들고 파생 클래스의 메서드를 호출하는 데 사용됩니다. 가상 기능은 런타임에 늦게 해결됩니다.
다음은 C++ 프로그램의 가상 기능 구현입니다. -
예시
#include <iostream>
using namespace std;
class B {
public:
virtual void s() { //virtual function
cout<<" In Base \n";
}
};
class D: public B {
public:
void s() {
cout<<"In Derived \n";
}
};
int main(void) {
D d; // An object of class D
B *b= &d; // A pointer variable of type B* pointing to d
b->s(); // prints"D::s() called"
return 0;
} 출력
In Derived