Ad Hoc Polymorphism  «Prev  Next»
Lesson 10 C++ Overloading functions
ObjectiveOverload function selection algorithm example

Overloaded Function Example in C++

Add a new print() function to the rational class that takes an integer argument representing the number of decimal places of precision to print.
Let us write an overloaded function greater() and follow the overload function selection algorithm for various invocations. In this example, the user-defined type rational is available and a variety of conversion rules, both implicit and explicit, are being applied.

Program dissection

Move your mouse cursor over the highlighted lines of code below for a pop-up discussion of their purpose.

C++ Overload
  1. This constructor converts from type double to type rational.
  2. This member function converts from type rational to type double.
  3. Three distinct functions are overloaded. The most interesting has rational type for its argument list variables and for its return type. The conversion member function "operator double" is required to evaluate w > z. Later in this course, we shall show how to overload "operator >()" to take rational types directly.
  4. The first statement selects the first definition of "greater" because of the exact match rule. The second statement selects the second definition of "greater" because of the use of a standard promotion conversion of float to double. The value of variable x is promoted to type double.
  5. The third definition of "greater" is selected because the required cast coerces i to be type rational. The explicit conversion of i to a rational is necessary to avoid ambiguity.| |The function call "greater(i, z)" would have to have two available conversions to achieve a match. The user-defined conversion of int to rational for the argument i matches the third definition. The user-defined conversion from rational to double for the argument z matches the second definition. This violates the uniqueness provision for matching when user-specified conversions are involved.
  6. This is an exact match for definition three.

Overloaded Function Algorithm
The output from this program is:
greater(10, 5) = 10
greater(7, 14.5) = 14.5
greater(10, 350 / 100) = 10
greater(10 / 1, 350 / 100) = 10 / 1

Overload Function - Exercise

Click the Exercise link below to overwrite the print() member function for the rational class.
Overload Function - Exercise