James Dickens James Dickens - 1 month ago 7
C++ Question

Constructors for Structs in C++

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 variables
B 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);

Answer

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.

Comments