Learn C++ - C++ Function Overloading






Function polymorphism, also called function overloading, allows us to call the same function by using varying numbers of arguments.

Function overloading can create multiple functions with the same name.

The polymorphism means having many forms.

The key to function overloading is a function's argument list, also called thefunction signature.

If two functions use the same number and types of arguments in the same order, they have the same signature. The variable names don't matter.

C++ enables you to define two functions by the same name, as long as the functions have different signatures.

The signature can differ in the number of arguments or in the type of arguments, or both.

Example

For example, you can define a set of print() functions with the following prototypes:

void print(const char * str, int width);  // #1 
void print(double d, int width);          // #2 
void print(long l, int width);            // #3 
void print(int i, int width);             // #4 
void print(const char *str);              // #5 

When you then use a print() function, the compiler matches your use to the proto- type that has the same signature:

print("a", 15);         // use #1 
print("a");             // use #5 
print(2020.0, 11);      // use #2 
print(2020, 12);        // use #4 
print(2020L, 15);       // use #3 

Example


// Overloaded functions. 
#include <iostream> 
using namespace std; 
//  w  w w . j av  a  2 s  . c  o  m
// function square for int values 
int square( int x ) 
{ 
    cout << "square of integer " << x << " is "; 
    return x * x; 
} // end function square with int argument 

// function square for double values 
double square( double y ) 
{ 
    cout << "square of double " << y << " is "; 
    return y * y; 
} // end function square with double argument 

int main() 
{ 
    cout << square( 7 ); // calls int version 
    cout << endl; 
    cout << square( 7.5 ); // calls double version 
    cout << endl; 
}

The code above generates the following result.





Note

The following signatures can't coexist.

double cube(double x); 
double cube(double & x); 

The function-matching process does discriminate between const and non-const variables as follows.

void d(char * bits);          // overloaded 
void d(const char *cbits);   // overloaded 

The function return type is not part of the signature of a function.

For example, the following two declarations are incompatible:

  long g(int n, float m);    // same signatures, 
double g(int n, float m);    // hence not allowed