Advertisement

C++ Program using virtual function


In this program, You will learn how to implement a virtual function in C++.


virtual void msg(){ 
   //statement
}

Example: How to implement a virtual function in C++

#include<iostream>
using namespace std;

class First {
public:

   virtual void msg() {
       cout << "Welcome";
   }
};

class Second : public First {
public:

   void msg() {
       cout << "Hello";
   }
};

int main() {

   First *f;
   Second s;
   f = &s;
   f->msg();

   return 0;
}

Output:

Hello