I came across the following practice question and answer while studying C++ and I do not understand it.
Given:
class B {}; struct A { A( B b ); };
Call the function void
test( A a, int* b=0);
with the two corresponding variablesB b, int i;
The answer is
test( b, &i );
My question is, how is it enough to pass the necessary parameter of the constructor and not actually call it? In my mind, the answer should have been:
test( A(b), &i);
This works because A
has a single-argument constructor, which C++ uses as a converting constructor:
A constructor that is not declared with the specifier
explicit
and which can be called with a single parameter (until C++11) is called a converting constructor. Unlike explicit constructors, which are only considered during direct initialization (which includes explicit conversions such as static_cast), converting constructors are also considered during copy initialization, as part of user-defined conversion sequence.
That is why C++ can interpret test(b, &i)
as test(A(b), &i)
.
If you do not want this behavior, mark A
's constructor explicit
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With