Function overriding in C++

Function overriding in C++

What is function overriding in C++?

Functions are the group of statements that are used to perform a specific task. Now if we want to know what is function overriding then we must also know what is inheritance as function overriding cannot be implemented without inheritance. So,inheritance is a feature in C++ that allows the child class to acquire the properties and functionality of parent class.

If we are using the concept of inheritance in our program and the derived class and base class have a function with the same name and same parameters, i.e. if we are providing a new definition to the already defined function of the parent class, then it is called function overriding. It is done at runtime hence, it is known as runtime polymorphism.  

Advantages of function overriding in C++

As we have discussed above what is function overriding, now lets look at some of its advantage :-

  • The child class having same function of parent class,can even have its independent implementation of that function.
  • Helps in saving the memory space.
  • Maintain consistency, and readability of our code.
  • Helps in making code re-usability easy.
  • The child class can access function of parent class as well.

C++ programming code to show function overriding

#include <iostream>
using namespace std;
 
class Volume //Base Class.
{ 
 
    public: 
 
    int square(int s)//Function declaration.
    {   
 
    cout<<"Volume="<<s*s*s<<endl;   
 
    }     
 
};  
 
class Area: public Volume  //Derived class 
 
{   
 
    public: 
 
    int square(int s)//Overridden function.   
 
    {   
 
       cout<<"Area="<<s*s<<endl;  
 
    }   
 
}; 
 
int main(void) 
{ 
    Volume v;
    Area a;
    v.square(5);//Base class function will be called.
    a.square(5);//Derived class function will be called.
     
 
   return 0; 
 
}
Output:
Volume=125
Area=25

Disadvantages of function Overriding in C++

After learning things about function overriding lets have a look on its disadvantage:-

  • Function overriding cannot be done within a same class. So, we need to do implement inheritance.
  • Static methods can never be overridden.
      • class Base
        {
        static  void fun()
        };
        class Derived : public Base
        {
         void fun()// error
        };