Function Overloading in C++

C++ allows you to overload functions, that is, different functions can have the same name in a program.

This is known as function polymorphism in oops. Overloading refers to the use of the same thing for different purposes . C++ also permits overloading functions .This means that we can use the same function name to creates functions that perform a variety of different tasks.

Using the concepts of function overloading , a family of functions with one function name but with different argument lists in the functions call .The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type.

Example:

int add(int a, int b);             //prototype 1
int add(int a, int b, int c);      //prototype 2
double add(double x, double y);    //prototype 3
double add(double p , double q);   //prototype 4

In our example four different function share the same name, add(). The function add() was overloaded for int and double types. The compiler uses a function’s signature to differentiate between overloaded functions.

When a function is called, A function signature comprises the number and type of parameters. The compiler compares the arguments to the signature of the overloaded functions and simply calls the appropriate function.

cout<<add(5,10);           //uses prototype 1
cout<<add(15,10.0);        //uses prototype 4
cout<<add(12.5,7.5);       //uses prototype 3
cout<<add(5,10,15);        //uses prototype 2

When overloaded functions are called, implicit type conversion takes place. However, this can lead to ambiguities, which in turn cause a compiler error to be issued.

Overloading Resolution:

  1. The compiler first tries to find an exact match in which the types of actual arguments are the same and use that function .
  2. If an exact match is not found the compiler uses the integral promotions to the actual arguments such as :
    • char to int
    • float to double
    • to find a match
  3. When either of them tails ,the compiler tries to use the built in conversions to the actual arguments and them uses the function whose match is unique. If the conversion is possible to have multiple matches, then the compiler will give error message.

Example:

long square (long n);
double square(double x);

A call square(10); Will cause an error because int argument can be converted to either long or double .There by creating an ambiguous situation as to which version of square( )should be used.

Example:

#include<iostream.h>
int volume(double,int);
double volume( double , int );
double volume(longint ,int ,int);
void main( )
{
       cout<<volume(10)<<endl;
       cout<<volume(10)<<endl; cout<<volume(10)<<endl;
}
int volume( ini s)
{
    return (s*s*s); //cube
}
double volume( double r, int h)
{
    return(3.1416*r*r*h); //cylinder
}
long volume (longint 1, int b, int h)
{
    return(1*b*h); //cylinder
}
output:
1000
157.2595
112500

Related posts