Virtual Functions and Runtime Polymorphism in C++

C++Server Side ProgrammingProgramming

Virtual functions in C++ use 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.

The main use of virtual function is to achieve Runtime Polymorphism. Runtime polymorphism can be achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘b’ contains the address of object ‘d’ of derived class.

Example Code

#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() {
         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 of type B* pointing to d
   b->s(); // prints "D::s() called"
   return 0;
}

Output

In Derived
raja
Published on 04-Apr-2019 13:55:58
Advertisements