Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors for Structs in C++

Tags:

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);
like image 297
IntegrateThis Avatar asked Oct 05 '16 03:10

IntegrateThis


1 Answers

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.

like image 106
Sergey Kalinichenko Avatar answered Sep 22 '22 13:09

Sergey Kalinichenko