In: Computer Science
In c++, when dealing with inheritance in a class hierarchy, a derived class often has the opportunity to overload or override an inherited member function. What is the difference? and which one is the better?
Function overloading:
Function overloading allows a class to have more than one function with the same name but different types or different numbers of parameters.
For example:
//function to calculate the sum of two integers
int sum(int a, int b)
{
return a+b;
}
//function to calculate the function of two float numbers
float sum(float a, float b)
{
return a+b;
}
Both of the above functions as the same name but different types of parameters. If we will pass integer parameters then the first function will be called, if passing the float type parameter then the second function will be called.
Function Overriding:
Function overriding is a feature used by the class when we are using inheritance. A subclass can override the method of the base class that is very similar and we modify the behavior as needed.
The child class overrides the parent class function.
It involves multiple classes and the parameter list must be the same.
Difference between function overloading and function overriding:
Which one is better depends upon the requirement. As per the suitable requirement, we must implement the overloding or overriding. The overriding is done at execution time, so we can say that overriding is better than overloading.