Function Overloading
Reading: Dietel section 3.20
- C++ allows more than one implementation of a given function name
Applies to member functions within the same class and nonmember functions- Want to allow the same type of operation for different types of arguments
int power ( int base, int exponent );
double power ( int base, double exponent );
Rational power ( Rational base, double exponent );- Versions are differentiated by :
Number / type of parameters
Const function vs. non-const function
Const vs. non-const parameter(s)
Rules for default parameters still apply- When compiler encounters a call, parameter list is used to find best match
Exact match of parameter list
Const version called on const objects, non-const on non-const
Const-parameter version used with const-type reference parameters, etc.- Cannot overload by return type only!
Syntax error
Compiler will not know which version to call- Caution: make sure versions are distinguishable ( especially with default parameters )
int myfunc ( double x, int y = 0 );
int myfunc ( double x, double y = 1.0);
int a = myfunc ( 8.7, 2 ); // First version called
int b = myfunc ( 8.7, 2.4 ); // Second version called
int x = myfunc ( 8.7 ); // Which version should be called? Syntax error!