0

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

Sven Williamson
  • 1,094
  • 1
  • 10
  • 19
  • 2
    `A a(2)` would not require a copy constructor. – juanchopanza Oct 27 '15 at 22:23
  • Even if the copy is (optionally) optimized out by the compiler, it has to check that the copy isn't private or deleted. Otherwise the code would just compile on systems doing the non-required optimization. See [What's the motivation behind having copy and direct initialization behave differently?](http://stackoverflow.com/questions/11223285/whats-the-motivation-behind-having-copy-and-direct-initialization-behave-differ) – Bo Persson Oct 27 '15 at 22:32
  • @mksteve That means it didn't work, because it shouldn't compile. – juanchopanza Oct 27 '15 at 22:32
  • @juanchopanza. I thought `A a = 2;` was the same as `A a(2);` ignoring occasional mistake by compiler that it was a declaration. – mksteve Oct 27 '15 at 22:36
  • @mksteve Not really although it is close. See the duplicate. – juanchopanza Oct 27 '15 at 22:36
  • @juanchopanza, I don't really see them as the same question - the other question may be created real objects, which need copying. This question talks about ints, which does not need a copy, and shouldn't require a copy constructor. Which compiler should I try to get the requires copy constructor behavior? – mksteve Oct 27 '15 at 22:40
  • @mksteve It is exactly the same thing. You can try any standards compliant compiler. GCC, CLANG spring to mind. – juanchopanza Oct 28 '15 at 06:52

0 Answers0