Copy constructor/Assignment operator confusion when initializing object

1.8k views Asked by At

What's the difference between doing this:

class_name object_name = something;

and

class_name object_name(something);

From what I read here, both use the copy constructor but I don't understand why that happens and how implicit conversions come into play. How I understood it (before reading about it) was that the first uses the default assignment operator (if not defined) by creating a temp object and then calls the copy constructor but that seems to be wrong. I am asking because I read that when making the copy constructor explicit, the first option will fail even if something is of class_name type, so the two options must be different enough. Also is the assignment operator used (using default or user-defined implementation) on top of the copy constructor in the 1st option or is it just a user-friendly syntax form of calling the copy constructor?

2

There are 2 answers

8
AudioBubble On

If the copy constructor is explicit, the first form could only be achieved by writing:

class_name object_name = class_name(something);

i.e. explicitly calling the copy constructor.

In the end, though, if the copy constructor is explicit, just use the first form if this is unambiguous (beware the most vexing parse), or for extra c++11 points use the brace initialiser syntax, which can never be ambiguous:

class_name object_name{something};

OR using Herb Sutter's "almost always auto" idea:

auto object_name = class_name{something};

To answer your other question, the assignment or copy-assignment operators are not used here. The copy-assignment operator is used where you are assigning a copy to a previously initialised variable:

class_name object_name;
object_name = class_name(something); // uses class_name& operator= (class_name& other)
0
AudioBubble On

The copy constructor and assignment operator are not the same thing.

   Test(const Test &t)
   {
      std::cout<<"Copy constructor called "<<std::endl;
   }
   Test& operator = (const Test &t)
   {
      std::cout<<"Assignment operator called "<<std::endl;
      return *this;
   }

  Test t1, t2;
  t2 = t1;
  Test t3 = t1;

In this example, the assignment operator is called for t2 = t1 and the copy constructor is called for t3 = t1.

If you make the copy constructor explicit, you have to invoke it like this:

Test t3(t1);