Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor or = operator?

Tags:

c++

    class Foo
    {


    };

    Foo f;
    Foo g = f; // (*)

My question is, what is being called in the line marked with (*) ? Is it the default copy ctr or '=' operator?

like image 770
Adam Varhegyi Avatar asked Jun 16 '13 12:06

Adam Varhegyi


People also ask

What is the difference between copy constructor and copy assignment operator in C++?

The main difference between copy constructor and assignment operator is that copy constructor is a type of constructor that helps to create a copy of an already existing object without affecting the values of the original object while assignment operator is an operator that helps to assign a new value to a variable in ...

Is copy constructor necessary?

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written (see Rule of three).


1 Answers

My question is, what is being called in the line marked with (*) ? Is it the default copy ctr or '=' operator?

The copy constructor will be called.

Even though the = sign is being used, this is a case of initialization, where the object on the left side is constructed by supplying the expression on the right side as an argument to its constructor.

In particular, this form of initialization is called copy-initialization. Notice, that when the type of the initializer expression is the same as the type of the initialized class object (Foo, in this case), copy-initialization is basically equivalent to direct-initialization, i.e.:

Foo g(f); // or even Foo g{f} in C++11

The subtle only difference is that if the copy constructor of Foo is marked as explicit (hard to imagine why that would be the case though), overload resolution will fail in the case of copy-initialization.

like image 177
Andy Prowl Avatar answered Sep 18 '22 18:09

Andy Prowl