The following will not compile unless copy constructor is made public. Yet, the compiler only ever calls the normal constructor. I would be very grateful if someone could explain to me the rationale for this, or tell me what I am missing. I have read the thread:
Explicit copy constructor behavior and pratical uses which focuses on implicit v explicit contructors and explains how only direct-initialization syntax will work for explicit constructors. But this thread does not seem to address the present case (I am sure it does but I fail to see why). Whether I use the direct initialization syntax A a(2);
or the copy-initialization syntax A a =2;
I would have though the compiler would only care about A(int)
and not about A(const A&)
.
class A {
// public: // uncomment or will not compile
A(const A&){std::cout<<"Even if public, I won't be called\n";}
int a;
public:
A(int a){this->a = a; std::cout <<"I alone will be called\n";}
};
int main(){A a = 2;} // A a(2); would work fine without public Ctor
Edit
Ok from the answer which has been suggested (thank you!):
Is there a difference in C++ between copy initialization and direct initialization?
The copy initialisation syntax A a = 2;
is semantically equivalent to a call to constructor A(int)
followed by a call to copy constructor A(const A&)
, and the latter has been optimized out by the compiler which explains why I am not seeing it. Thank you very much