Lesson 10 C++ Overloading functions
Objective Overload 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.
Move your mouse cursor over the highlighted lines of code below for a pop-up discussion of their purpose.
This constructor converts from type double to type rational.
This member function converts from type rational to type double.
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.
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.
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.
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