Function Overloading vs Function Overriding in C++

Difference between function overloading and function overriding in C++: In the before sections, as we have already learned in detail regarding function overloading and function overriding. Now, let us learn the differences between them.

Difference between function overloading and function overriding in C++

Overloading Overriding
A prototype of overloading is totally dependent on the number of parameters All the prototyping aspects are constant
We do not require any kind of special keyword In overriding, the function in the base class needs to be preceded with ‘virtual’ keyword in order to be overridden in the child class
Overloading can take place without any inheritance Overriding of functions can be done when one class is inherited by other class
The overloaded functions are always in the same scope All overriding functions are in different scope always
Overloading is used to have the same names of various functions which act distinctively relying on parameters with them It is required when a determined class function needs to perform some additional (or) unexpected job in comparison to base class function
Overloading is done at the compile time Overriding is done at runtime

 Example: for overloading

#include<iostream> 
using namespace std; 
//overloaded functions 
void test(int); 
void test(float); 
void test(int, float);  
int main() 
{ 
    int a = 5; 
    float b = 5.5; 
//Overloaded functions 
//with different type and 
//number of parameters 
    test(a); 
    test(b); 
    test(a, b); 
    return 0; 
} 
  
//Method 1 
void test(int var) 
{ 
    cout<<"Integer number: "<< var <<endl; 
} 
//Method 2 
void test(float var) 
{ 
    cout<<"Float number:"<< var <<endl; 
} 
//Method 3 
void test(int var1, float var2) 
{ 
    cout<<"Integer number:"<<var1; 
    cout<<"and float number:"<<var2; 
}

Output:

Integer number: 5
Float number: 5.5
Integer number: 5 and float number:5.5



Example: for Overriding

#include<iostream> 
using namespace std;   
class BaseClass 
{ 
public: 
    virtual void Display() 
    { 
        cout<<"\nThis is Display( ) method of BaseClass"; 
    } 
    void Show() 
    { 
        cout<<"\nThis is Show( ) method of BaseClass"; 
    } 
}; 
  
class DerivedClass : public BaseClass 
{ 
public: 
  //Overriding method - new working of 
 //base class's display method 
    void Display() 
    { 
      cout<<"\nThis is Display() method of DerivedClass"; 
    } 
}; 
//Driver code 
int main() 
{ 
    DerivedClass dr; 
    BaseClass &bs = dr; 
    bs.Display(); 
    dr.Show(); 
} 

Output:

This is Display() method of DerivedClass
This is Show() method of BaseClass