Hey this is a really basic question and but I got confused about it. Say I created an object
MyObject a.
It comes with a copy constructor, so I know I can do this:
MyObject b(a);
But can I do this?
MyObject& b(a);
And if I do this:
MyObject b = a; what is in b? Apology if this question is too fundamental to be bothered posting.
Doing
MyObject& b(a)has nothing to do with the copy constructor. It just createsbwhich is a reference to the objecta. Nothing is copied. Think ofbas an alias for the objecta. You can usebandaequivalently from then on to refer to the same object.MyObject b = a;will use the copy constructor, just asMyObject b(a);would.There are two forms of initialisation:
T x = a;is known as copy-initialization;T x(a)andT x{a}are known as direct-initialization.When
Tis a reference type, it doesn’t matter which type of initialisation is used. Both have the same effect.When
Tis a class type, we have two possibilities:If the initialisation is direct-initialization (
MyClass b(a);), or, if it is copy-initialization withabeing derived from or the same type asT(MyClass b = a;): an applicable constructor ofTis chosen to construct the object.As you can see, both of your examples fall in this category of class type initialisers.
If the initialisation is any other form of copy-initialization, any user-defined conversion sequence will be considered followed by a direct-initialization. A user-defined conversion sequence is basically any sequence of standard conversions with a single conversion constructor thrown in there.
If
cwere ofFooclass type and there was a conversion constructor fromFootoMyClass, thenMyClass b = c;would be equivalent toMyClass b(MyClass(c));.So basically, if the source and destination types are the same, both forms of initialisation are equivalent. If a conversion is required, they are not. A simple example to show this is:
The output for this program (with copy elision disabled) is:
Of course, there are lots of other types of initialisations too (list initialisation, character arrays, aggregates, etc.).