-1

if I create three objects like this:

A myA; // line 1
A myA2 = A(); // line 2
A myA3 = myA; // line 3

I thought in the second line the copy constructor is called. But if I try this (Visual Studio) line 1 and line 2 calls only the default constructor. Whereas of course line 3 calls the copy constructor. So it seems there is no difference between line 1 and line 2. Both calls the default construcor. So why I have the different syntax?

By the way my testclass A has the form:

class A { 
  public:
   A() { cout << "default ctor is called..." << endl; }
   A(const A &obj) { cout << "copy ctor is called..." << endl; }
};
knowledge
  • 941
  • 1
  • 11
  • 26

1 Answers1

0

The copy constructor calling is optimized according to copy elision; which is guaranteed since C++17.

In initialization, if the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object

songyuanyao
  • 169,198
  • 16
  • 310
  • 405