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?
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 ...
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With