Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 가상 함수

<시간/>

이 튜토리얼에서는 C++의 가상 함수를 이해하는 프로그램에 대해 논의할 것입니다.

가상 함수는 기본 클래스에서 정의된 멤버 함수이며 자식 클래스에서도 추가로 정의할 수 있습니다. 파생 클래스를 호출하는 동안 덮어쓴 함수가 호출됩니다.

예시

#include <iostream>
using namespace std;
class base {
   public:
   virtual void print(){
      cout << "print base class" << endl;
   }
   void show(){
      cout << "show base class" << endl;
   }
};
class derived : public base {
   public:
   void print(){
      cout << "print derived class" << endl;
   }
   void show(){
      cout << "show derived class" << endl;
   }
};
int main(){
   base* bptr;
   derived d;
   bptr = &d;
   //calling virtual function
   bptr->print();
   //calling non-virtual function
   bptr->show();
}

출력

print derived class
show base class