Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time)
Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role.
- It can be done in base as well as derived class
.Example:
void area(int a);
void area(int a, int b);
CPP
#include <iostream>
using namespace std;
void test( int );
void test( float );
void test( int , float );
int main()
{
int a = 5;
float b = 5.5;
test(a);
test(b);
test(a, b);
return 0;
}
void test( int var)
{
cout << "Integer number: " << var << endl;
}
void test( float var)
{
cout << "Float number: " << var << endl;
}
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
Function Overriding (achieved at run time)
It is the redefinition of base class function in its derived class with same signature i.e. return type and parameters.
- It can only be done in derived class.
- Example:
Class a
{
public:
virtual void display(){ cout << "hello"; }
};
Class b:public a
{
public:
void display(){ cout << "bye";}
};
CPP
#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 :
void Display()
{
cout << "\nThis is Display() method"
" of DerivedClass" ;
}
};
int main()
{
DerivedClass dr;
BaseClass &bs = dr;
bs.Display();
dr.Show();
}
|
Output
This is Display() method of DerivedClass
This is Show() method of BaseClass
Function Overloading
|
Function Overriding
|
Function Overloading provides multiple definitions of the function by changing signature. |
Function Overriding is the redefinition of base class function in its derived class with same signature. |
An example of compile time polymorphism. |
An example of run time polymorphism. |
Function signatures should be different. |
Function signatures should be the same. |
Overloaded functions are in same scope. |
Overridden functions are in different scopes. |
Overloading is used when the same function has to behave differently depending upon parameters passed to them. |
Overriding is needed when derived class function has to do some different job than the base class function. |
A function has the ability to load multiple times. |
A function can be overridden only a single time. |
In function overloading, we don’t need inheritance. |
In function overriding, we need an inheritance concept. |
Last Updated :
08 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...