Virtual Function in C++

Virtual Function


Here, in this section we will discuss about virtual function in C++.

Definition of virtual function: Virtual function is a special Member function that is declared within a base class and redefined by the derived class to go with its own task

virtual function in C++

Virtual functions give programmer capability to call a member function of a different class  by the same function call based on a different situation.

  • In other words, a virtual function is a function which gets override in a derived class and instructs c++ compiler for executing late binding on that function
  • A function call is resolved at runtime in late binding and so that compiler determines the type of an object at runtime.
  • Virtual function syntax

    class class_name 
      virtual return fucntion_name(arg...) 

C++ program to demonstrate the usage of virtual keyword

using namespace std;

class parent//parent class
  virtual void show()
    cout << "Base class\n";

class child:public parent//child class
  public:  void show()
     cout << "Derived Class";

int main()
  parent* p; //Base class pointer
  child c; //Derived class object
  p = &c;; //Late Binding Occurs
Derived class
When we have used virtual keyword with the base class function dynamic binding takes place and the child version of the function will be called because parent class points to Child class object The output of the above program without using the virtual keyboard O/P
Base class
  • Here we have declared parent class  and assigned child class object but still, base class pointer reference will point the base class function show()
  • To overcome this problem we will use the virtual keyword.

Advantage of virtual functions

Ambiguity in function calls is reduced because It can call all the required functions from parent and child class in a different context

Some points to note about virtual functions

  • Members of some class virtual functions cannot be static
  • The virtual function can be defined in the parent class even if it is not used
  • The declaration of the virtual function of parent class in the child class must be identical, if the prototype is not identical c++ will consider them as overloaded functions
  • A virtual constructor is not possible whereas a virtual destructor is possible