Virtual Function definition and example


 

A virtual declared within a base class and isOverride by a derived class. Sometime derived class object using a pointer or a reference to the base class,then due to early binding it always calling base call function.

  • Virtual functions make sure that the correct function is called. 
  • Functions are declared with a virtual keyword in base class.
  • The resolving of function call is done at run time not in compile time.

Keypoints

  1. Virtual functions should not be static or friend function class.
  2. Virtual functions should be accessed using pointer.
  3. A class should not have  virtual constructor.
This is base class  print function:
This is show function is base class
This is problem for early binding.To make sure correct function is working we need late binding to make sure everthing is correct.we use virutal keyword.See below same code with some changes.


This is derived class  print function:
This is show function is derived class

0 Comments