Function Overloading in C++: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations in the same scope. Such implementations are more useful to do different task with same function.
Using the concept of function overloading; we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number of the arguments but not on the function type.
For example, consider the following c++ program where the function add() is overloaded.
int add(int, int);
int add(int,int,int);
double add(double, double);
int main()
{
cout<
cout<
cout<
return 0;
}
int add(int a, int b)
{
return(a+b);
}
int add(int a, int b, int c)
{
return(a+b+c);
}
double add( double x, double y)
{
return(x+y);
}
How overloaded function are executed?
A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must be unique. It not matched arguments list is found, it tries to perform type conversion otherwise it generate an error message.
Overloading Considerations
Function Declaration Element | Used for Overloading? | |
---|---|---|
Function return type | No | |
Number of arguments | Yes | |
Type of arguments | Yes | |
Presence or absence of ellipsis | Yes | |
Use of typedef names | No | |
Unspecified array bounds | No | |
const or volatile (see below) | Yes |
Although functions can be distinguished on the basis of return type, they cannot be overloaded on this basis.
Const
or volatile
are only used as a basis for overloading if they are used in a class to apply to the this pointer for the class, not the function's return type. In other words, overloading applies only if the const or volatile
keyword follows the function's argument list in the declaration.
References:
2. OOPs with C++ E Balagurusamy
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.