Function Overloading

A single function name can have multiple declarations. If those declarations specify different function signatures, the function name is overloaded. A function call to an overloaded function requires the compiler to resolve the overloaded name and decide which function to call. The compiler uses the argument types (but not the return type) to resolve calls to overloaded functions. Example 5-11 shows simple examples of two overloaded functions named sqrt: one for int arguments and the other for double arguments. The rest of this section explains the rules for overloading and resolution.

Example 5-11. Overloaded functions
int sqrt(int);
double sqrt(double);

int main(  )
{
  std::cout << sqrt(3) << '\n';    // sqrt(int)
  std::cout << sqrt(3.14) << '\n'; // sqrt(double)
}

Declaring Overloaded Functions

Whenever you declare more than one function with the same name in the same scope, you are overloading the function name. The function can be an ordinary function, member function, constructor, or overloaded operator.

Overloaded functions must differ in their parameter lists: they must have a different number of parameters, or the parameter types must be different. Refer to Section 5.2.2 earlier in this chapter for information on equivalent parameter types.

Default arguments are not considered when declaring overloaded functions (but are important when resolving a call to an overloaded function, as described in Section 5.3.2). Example 5-12 shows overloaded constructors and member ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.