c++initializationcopy-constructorcopy-initialization

To Clarify my insights to copy initialization and direct initialization


Define a class as follows:

class A {
public:
  A(): s("") {}                             //default constructor
  A(const char* pStr): s(pStr) {}           //constructor with parameter
  A(const A& a) : s(a.s) {}                 //copy constructor
  ~A() {}                                   //destructor
private:
  std::string s;
};

The code below will execute direct initialization:

A a1("Hello!");   //direct initialization by calling constructor with parameter
A a2(a1);          //direct initialization by calling copy constructor

And what follows will execute copy initialization:

A a3 = a1;  
A a4 = "Hello!";

To my understanding, A a4 = "Hello" is equivalent to:

//create a temporary object first, then "copy" this temporary object into a4 by calling copy constructor    
A temp("Hello!");    
A a4(temp);

So what is the difference between A a3 = a1 and A a2(a1)? It seems they both call copy constructor. And whether are my comments above right? (given no compiler optimization)


Solution

  • There's a difference between direct-initialization and copy-initialization:

    Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

    So if you make the copy constructor explicit then A a3 = a1 won't work; while A a2(a1) still works fine.