Overloading Functions

You can overload a function by having multiple declarations of the same function name in the same scope. The declarations differ in the type and number of arguments in the argument list. When an overloaded function is called, the correct function is selected by comparing the types of the actual arguments with the types of the formal arguments.

Consider a function print, which displays an int. As shown in the following example, you can overload the function print to display other types, for example, double and char*. You can have three functions with the same name, each performing a similar operation on a different data type.

// This example illustrates function overloading.

#include <iostream.h>

void print(int i) { cout << " Here is int " << i << endl; }
void print(double  f) { cout << " Here is float "
                                  << f << endl; }
void print(char* c) { cout << " Here is char* " << c << endl; }
void main() {
      print(10);            // calls print(int)
      print(10.10);         // calls print(double)
      print("ten");         // calls print(char*)
}

Two function declarations are identical if all of the following are true:


When you declare a function name more than once in the same scope, the second declaration of the function name is interpreted by the compiler as follows:



Argument Matching in Overloaded Functions
Scope in C++


Restrictions on Overloaded Functions
Member Functions