Reputation: 351
I was pretty sure the calling of B(A()) will call the defined constructor of B in my code. But I was surprised to find out that it didn't call to my constructor B and of course didn't print "Constructor B".
So, to which constructor this code is calling (what is the signature of this constructor that it's calling to)?
struct A
{
};
struct B
{
B(const A a) { std::cout << "Constructor B" << std::endl; }
};
int main()
{
B(A());
return 0;
}
Upvotes: 1
Views: 69
Reputation: 173014
It doesn't construct an object with type B
as you expected, then no constructor is called.
When declaring variables we can add (unnecessary) parentheses around the variable name, i.e. int (a);
has the same effect as int a;
. Similarly, B(A());
is same as B A();
, which declares a function named A
, which takes no parameters and returns B
.
As the workaround you can change ()
to {}
, e.g.
B(A{});
B{A()};
B{A{}};
Upvotes: 1