Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Virtual Functions Implementation in C++



Virtual functions in C++ used to create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. Virtual functions are resolved late, at runtime.

Here is an implementation of virtual function in C++ program −

Example

#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;
}

Output

In Derived
Updated on: 2019-07-30T22:30:25+05:30

682 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements