Difference between function overloading and function overriding in C ++

Difference between function overloading and function overriding in C++

What is difference between function overloading and function overriding?

Function overloading is a concept using which we define two or more functions in the same class with the same name with a condition that the parameters of the function should differ by its number or type.

Function overriding is a concept using which we define two functions with the same name and same parameters with a condition that one function must present in a base class and other function in a derived class. 

Function Overloading

  • Functions have same name but different number or different type of parameters.

  • Overloading of the functions take place at compile time.

  • It is also known as compile time polymorphism.

  • The functions that are overloaded are present in same class.

  • It can occur without inheritance.

  • Functions can have different data types.

Function Overloading

Function Overriding

  • Functions have same name ,same number and same type of parameters.

  • Overriding of the functions take place at run time.

  • It is also known as run time polymorphism.

  • The functions that are overridden are present in different class.

  • It cannot occur without inheritance.

  • Functions should have same data types.

Function Overriding

C++ program to show function overloading

#include <iostream>
 
using namespace std;
void superhero(string str) //First definition.
{
    cout<<"My favourite movie is "<<str <<endl;
 
}
 
void superhero(string str1,string str2)//Second definition.
{
    cout<<"My favourite movie is "<<str1<<" vs "<<str2<<endl;
    
}

 
int main()
{
    superhero("Ironman");
    //Passing value for first defination.
 
    superhero("Superman","Batman");
    //Passing value for second defination.
 
}
Output:
My favourite movie is Ironman
My favourite movie is Superman vs Batman

C++ program to show function
overriding

#include <iostream>
using namespace std;
class Marvel { //Base Class. 
    public: 
    void fav(string s)//Function declaration.
    {   
    cout<<"My favorite is "<<s<<endl;   
    }     
};  
class Dc: public Marvel {  //Derived class   
    public: 
    void fav(string s)//Overridden function.   
    {   
       cout<<"My favorite is "<<s<<endl;  
    }   
}; 
int main() { 
    Marvel m;
    Dc d;
    m.fav("Marvel");
    //Base class function will be called.
    d.fav("Dc");
    //Derived class function will be called.
    return 0; 
}
Output:
My favorite is Marvel
My favorite is Dc

Conclusion:

Function overloading and function overriding are used at the specific scenario. There is no such thing that function overloading is best or function overriding is best. We need to understand where to use them in our program. The above explanation and example will help us to understand the scenario where we can use them.