Constructors for structures in C ++

I studied the following practical question and answer while studying C ++, and I don't understand it.

Given:

class B {}; struct A { A( B b ); }; 

Call the function void test( A a, int* b=0); with two corresponding variables B b, int i;

Answer: test( b, &i );

My question is, is it enough to pass the required constructor parameter and not really name it? In my opinion, the answer should be:

 test( A(b), &i); 
+6
source share
1 answer

This works because A has a single argument constructor, which C ++ uses as the transform constructor:

A constructor that is not declared by the explicit specifier and which can be called with one parameter (before C ++ 11) is called a conversion constructor. Unlike explicit constructors, which are only considered in direct initialization (including explicit conversions such as static_cast), transform constructors are also considered during copy initialization as part of a custom transform sequence.

This is why C ++ can interpret test(b, &i) as test(A(b), &i) .

If you do not want this behavior, mark the A constructor explicit .

+8
source

All Articles