Accidentally Using a Single-Argument Constructor as a Conversion Constructor

The program (Fig. 10.12) uses the Array class of Figs. 10.1010.11 to demonstrate an improper implicit conversion. To allow this implicit conversion, we removed the explicit keyword from line 14 in Array.h (Fig. 10.10).


 1   // Fig. 10.12: fig10_12.cpp
 2   // Single-argument constructors and implicit conversions.
 3   #include <iostream>
 4   #include "Array.h"
 5   using namespace std;
 6
 7   void outputArray( const Array & ); // prototype
 8
 9   int main()
10   {
11      Array integers1( 7 ); // 7-element Array
12      outputArray( integers1 ); // output Array integers1
13      outputArray( 3 ); // convert 3 to an Array and output Array's contents
14   }  // end main
15
16   // print Array contents
17   void outputArray( const Array &arrayToOutput )
18   {
19      cout << "The Array received has " << arrayToOutput.getSize()
20         << " elements. The contents are: " << arrayToOutput << endl;
21   } // end outputArray


The Array received has 7 elements. The contents are:
           0           0           0           0
           0           0           0

The Array received has 3 elements. The contents are:
           0           0           0


Fig. 10.12. Single-argument constructors and implicit conversions.

Line 11 in main (Fig. 10.12) instantiates Array object integers1 and calls the single-argument constructor with the int value 7 to specify the number of elements in the Array. Recall from Fig. 10.11 that the Array constructor that receives an int argument initializes all the Array elements to 0. Line 12 calls function outputArray (defined in lines 17–21), which receives as its argument a const Array & to an Array. The function outputs the number of elements in its Array argument and the contents of the Array. In this case, the size of the Array is 7, so seven 0s are output.

Line 13 calls function outputArray with the int value 3 as an argument. However, this program does not contain a function called outputArray that takes an int argument. So, the compiler determines whether class Array provides a conversion constructor that can convert an int into an Array. Since the Array constructor receives one int argument, the compiler assumes that the constructor is a conversion constructor that can be used to convert the argument 3 into a temporary Array object containing three elements. Then, the compiler passes the temporary Array object to function outputArray to output the Array’s contents. Thus, even though we do not explicitly provide an outputArray function that receives an int argument, the compiler is able to compile line 13. The output shows the contents of the three-element Array containing 0s.

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

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