void print( int & a ){ cout << a << endl; }
void print( const int & a ){ cout << 2*a << endl; }
void print( float a ){ cout << 3*a << endl; }
Why is 2
the output of print(1)
?
void print( int & a ){ cout << a << endl; }
void print( const int & a ){ cout << 2*a << endl; }
void print( float a ){ cout << 3*a << endl; }
Why is 2
the output of print(1)
?
The tenet of this question is that you need to know that anonymous temporaries cannot bind to non-const
references, and they can bind to const
references.
1 is an anonymous temporary of type int
.
Hence the const int&
binding is favoured by overload resolution.
Some compilers (older MSVC) would allow, in error, a binding to int&
. In standard C++, if the const int&
overload is missing, then the float
overload will be called.
For all three overloads:
void print( int & a ){ cout << a << endl; }
) The first overload is not called, since it only accepts a variable. (Unless you have an old MSVC compiler).void print( const int & a )
) The second overload is of type const int&
, which can accept either a temporary of type int, or a variable of type int.void print( float a )
) The third overload has an argument of type float, which would work be called if there was no overload of type int.Thus, since there is an overload that accepts a temporary variable of type int, the second overload is chosen over the third.