C++ Virtual Function

October 27, 2015 Posted by WithU Technologies
The member function which is declared within the base class and then redefined by a derived class by using the same function name.

To create a virtual function, we need to precede the base class member function with the virtual keyword:

 //Base Class
class Cars {

public:

 virtual void SetPower(){

 }

 };

·         When the virtual function is inherited from the base class, the derived class redefined the virtual function to suit its own needs.

·         Normally without the virtual functions, the base class pointer points to derived class objects.

·         In this case, when we use base class pointer to call a function which is in both classes, then base class function is invoked rather than the derived class.

·         But if we want to invoke the derived classes using base class pointer, then we declare virtual function in the base class.

Example:

#include <iostream>
using namespace std;

//Base Class

class Cars {

public:

 virtual void SetPower(){

    cout<<"Cars is the Base Class and we can implement this message also"<<endl;

 }

 };

//Derived Class

 class HyundaiCreta:public Cars

 {

 public:

    void SetPower(){  //using the same function name, used as virtual function in base class

          cout<<"Hyundai's SUV is expected to come with a refined 1.6-litre diesel engine making 126bhp and 26.5kgm of torque."<<endl;

    }

 };

 //Derived Class

 class RenaultDuster:public Cars

 {

 public:

    void SetPower(){   //Using the same function name, which is used as virtual function

          cout<<"Renault offers a 108.5bhp, 1.5-litre petrol motor with a torque figure of 25.3kgm."<<endl;

    }

 };





int main() {

   //two objects created

   HyundaiCreta h;

   RenaultDuster r;

   Cars c;



   //Pointer address to the objects created by derived class

   Cars *c1 = &h;

   Cars *c2 = &r;

   Cars *c3 = &c;



   //Arrow selection operator is used to call the redefined function through pointer

   c1->SetPower();

   c2->SetPower();

   c3->SetPower();

   return 0;

}



/*

Output:

Hyundai's SUV is expected to come with a refined 1.6-litre diesel engine making 126bhp and 26.5kgm of torque.

Renault offers a 108.5bhp, 1.5-litre petrol motor with a torque figure of 25.3kgm.

Cars is the Base Class and we can implement this message also



 */

·         Here we redefined the base class function using the virtual function which invoke the derived class functions using base class pointers.

·         All the three functions declared here are with the exact same name which is essential to support virtual functions.

·         Here we get three sentences as output, first two for the derived classes and last one for the base class.

·         if we need to invoke the base class along with the derived classes then we can also do that using virtual functions.