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.
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access