Overloaded square Functions

Figure 6.22 uses overloaded square functions to calculate the square of an int (lines 7–11) and the square of a double (lines 14–18). Line 22 invokes the int version of function square by passing the literal value 7. C++ treats whole number literal values as type int. Similarly, line 24 invokes the double version of function square by passing the literal value 7.5, which C++ treats as a double. In each case the compiler chooses the proper function to call, based on the type of the argument. The last two lines of the output window confirm that the proper function was called in each case.


 1   // Fig. 6.22: fig06_22.cpp
 2   // Overloaded square functions.
 3   #include <iostream>
 4   using namespace std;
 5
 6   // function square for int values              
 7   int square( int x )                            
 8   {                                              
 9      cout << "square of integer " << x << " is ";
10      return x * x;                               
11   } // end function square with int argument     
12
13   // function square for double values           
14   double square( double y )                      
15   {                                              
16      cout << "square of double " << y << " is "
17      return y * y;                               
18   } // end function square with double argument  
19
20   int main()
21   {
22      cout << square( 7 ); // calls int version
23      cout << endl;
24      cout << square( 7.5 ); // calls double version
25      cout << endl;
26   } // end main


square of integer 7 is 49
square of double 7.5 is 56.25


Fig. 6.22. Overloaded square functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset