Method overloading in C++ allows you to define multiple functions in a class with the same name but different parameters.
- Different parameter lists: Method overloading enables you to create multiple functions within a class with the same name but different parameter lists. C++ distinguishes between these functions based on the number, types, and order of parameters. This allows you to provide different behavior for a function depending on the input arguments.
- Compile-time resolution: The selection of the appropriate overloaded function is resolved at compile time based on the arguments provided during the function call. This means that the compiler determines which version of the overloaded function to invoke based on the arguments' types and the function's parameter signature.
- Return type does not matter: Overloaded functions can have different return types, but this alone is not sufficient to differentiate them. The compiler primarily relies on the parameter list for distinguishing between overloaded functions. This feature is known as "return type overloading."
Example:
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
void add(int x,int y){
cout<<"addition= "<<(x+y)<<endl;
}
void add(int x,int y,int z){
cout<<"addition = "<<(x+y+z)<<endl;
}
void add(int x,double d){
cout<<"addition = "<<(x+d)<<endl;
}
int main() {
add(2,3);
add(2,3,5);
add(2,2.5);
return 0;
}