The reason we’ve been declaring every single-argument contructor preceded by the keyword explicit is to suppress implicit conversions via conversion constructors when such conversions should not be allowed. A constructor that’s declared explicit
cannot be used in an implicit conversion. In the example of Figure 10.13, we use the original version of Array.h
from Fig. 10.10, which included the keyword explicit
in the declaration of the single-argument constructor in line 14
explicit Array( int = 10 ); // default constructor
Figure 10.13 presents a slightly modified version of the program in Fig. 10.12. When this program in Fig. 10.13 is compiled, the compiler produces an error message indicating that the integer value passed to outputArray
in line 13 cannot be converted to a const Array &
. The compiler error message (from Visual C++) is shown in the output window. Line 14 demonstrates how the explicit constructor can be used to create a temporary Array
of 3
elements and pass it to function outputArray
.
1 // Fig. 10.13: fig10_13.cpp
2 // Demonstrating an explicit constructor.
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 outputArray( Array( 3 ) ); // explicit single-argument constructor call
15 } // end main
16
17 // print Array contents
18 void outputArray( const Array &arrayToOutput )
19 {
20 cout << "The Array received has " << arrayToOutput.getSize()
21 << " elements. The contents are:
" << arrayToOutput << endl;
22 } // end outputArray
c:ooks2012cpphtp9examplesch10fig10_13fig10_13.cpp(13): error C2664:
'outputArray' : cannot convert parameter 1 from 'int' to 'const Array &'
Reason: cannot convert from 'int' to 'const Array'
Constructor for class 'Array' is declared 'explicit'