Skip to main content

C++ Function Overriding & Virtual Function

C++ Function Overriding

If derived class defines same function as defined in its base class, it is known as function overriding in C++. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the function which is already provided by its base class.

C++ Function Overriding Example

Let's see a simple example of Function overriding in C++. In this example, we are overriding the eat() function.

  1. #include <iostream>  
  2. using namespace std;  
  3. class Animal {  
  4.     public:  
  5. void eat(){    
  6. cout<<"Eating...";    
  7.     }      
  8. };   
  9. class Dog: public Animal    
  10. {    
  11.  public:  
  12.  void eat()    
  13.     {    
  14.        cout<<"Eating bread...";    
  15.     }    
  16. };  
  17. int main(void) {  
  18.    Dog d = Dog();    
  19.    d.eat();  
  20.    return 0;  
  21. }  

Output:

Eating bread...

C++ virtual function

  • A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword.
  • It is used to tell the compiler to perform dynamic linkage or late binding on the function.
  • There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived class object, always executes the base class function. This issue can only be resolved by using the 'virtual' function.
  • A 'virtual' is a keyword preceding the normal declaration of a function.
  • When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer.

Late binding or Dynamic linkage

In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call.


Rules of Virtual Function

  • Virtual functions must be members of some class.
  • Virtual functions cannot be static members.
  • They are accessed through object pointers.
  • They can be a friend of another class.
  • A virtual function must be defined in the base class, even though it is not used.
  • The prototypes of a virtual function of the base class and all the derived classes must be identical. If the two functions with the same name but different prototypes, C++ will consider them as the overloaded functions.
  • We cannot have a virtual constructor, but we can have a virtual destructor
  • Consider the situation when we don't use the virtual keyword.
  1. #include <iostream>  
  2. using namespace std;  
  3. class A  
  4. {  
  5.    int x=5;  
  6.     public:  
  7.     void display()  
  8.     {  
  9.         std::cout << "Value of x is : " << x<<std::endl;  
  10.     }  
  11. };  
  12. class B: public A  
  13. {  
  14.     int y = 10;  
  15.     public:  
  16.     void display()  
  17.     {  
  18.         std::cout << "Value of y is : " <<y<< std::endl;  
  19.     }  
  20. };  
  21. int main()  
  22. {  
  23.     A *a;  
  24.     B b;  
  25.     a = &b;  
  26.    a->display();  
  27.     return 0;  
  28. }  

Output:

Value of x is : 5

In the above example, * a is the base class pointer. The pointer can only access the base class members but not the members of the derived class. Although C++ permits the base pointer to point to any object derived from the base class, it cannot directly access the members of the derived class. Therefore, there is a need for virtual function which allows the base pointer to access the members of the derived class.

C++ virtual function Example

Let's see the simple example of C++ virtual function used to invoked the derived class in a program.

  1. #include <iostream>    
  2. {    
  3.  public:    
  4.  virtual void display()    
  5.  {    
  6.   cout << "Base class is invoked"<<endl;    
  7.  }    
  8. };    
  9. class B:public A    
  10. {    
  11.  public:    
  12.  void display()    
  13.  {    
  14.   cout << "Derived Class is invoked"<<endl;    
  15.  }    
  16. };    
  17. int main()    
  18. {    
  19.  A* a;    //pointer of base class    
  20.  B b;     //object of derived class    
  21.  a = &b;    
  22.  a->display();   //Late Binding occurs    
  23. }    

Output:

Derived Class is invoked  

Pure Virtual Function

  • A virtual function is not used for performing any task. It only serves as a placeholder.
  • When the function has no definition, such function is known as "do-nothing" function.
  • The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function declared in the base class that has no definition relative to the base class.
  • A class containing the pure virtual function cannot be used to declare the objects of its own, such classes are known as abstract base classes.
  • The main objective of the base class is to provide the traits to the derived classes and to create the base pointer used for achieving the runtime polymorphism.

Pure virtual function can be defined as:

  1. virtual void display() = 0;   

Let's see a simple example:

  1. #include <iostream>  
  2. using namespace std;  
  3. class Base  
  4. {  
  5.     public:  
  6.     virtual void show() = 0;  
  7. };  
  8. class Derived : public Base  
  9. {  
  10.     public:  
  11.     void show()  
  12.     {  
  13.         std::cout << "Derived class is derived from the base class." << std::endl;  
  14.     }  
  15. };  
  16. int main()  
  17. {  
  18.     Base *bptr;  
  19.     //Base b;  
  20.     Derived d;  
  21.     bptr = &d;  
  22.     bptr->show();  
  23.     return 0;  
  24. }  

Output:

Derived class is derived from the base class.

In the above example, the base class contains the pure virtual function. Therefore, the base class is an abstract base class. We cannot create the object of the base class.

Anurag Rana

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&