The Overloading Mechanism

Overloading Functions

C++ allows multiple functions to share the same name, provided that their parameter lists differ sufficiently so as to allow them to be distinguished from one another. Two functions that share the same name and that are defined in the same scope are said to overload the function name. The underlying mechanism used to achieve this is name mangling. Name mangling combines the name of a function with the types of the parameters occurring in its parameter list. The names of all C++ functions are mangled. Apart from allowing two functions to share the same name, name mangling also provides a facility for checking parameter types; thus, the C++ function call mechanism is type safe.

The following example demonstrates the overloading of a function name.

void f(int);
void f(double);
f(1);    // calls void f(int);
f(1.0);  // calls void f(double);

The following considerations apply to overloading function names.


void f(int);        // declares f to accept an integer
int f(int);         // syntax error ! only return type differs from previous f.

void g(int);        // declares g to accept an integer
void g(int&);       // syntax error ! int and int& not distinguishable
typedef int value;
void h(int);        // declares h to accept integer
void h(value);      // identical to: void h(int)
                    // because only superficial differences exist.
enum name {e};
void i(int);        // declares i to accept integer
void i(name);       // overloads i - name different from integer
void j(char*);      // declares j to accept char*
void j(char[]);     // identical to: void j(char*)
void j(char[3]);    // identical to: void j(char*)
void k(char(*)[3]);
void k(char[7][3]); // identical to:   void k(char(*)[3])
void k(char(*)[5]); // different from: void k(char(*)[3])