Let's say i'm having a copying contructor
1st way :
Car(Car const& other)
: Model{other.Model}, Something{other.Something}
{}
2nd way:
Car(Car const& other)
{
Model = other.Model;
Something = other.Something;
}
Let's say i'm having a copying contructor
1st way :
Car(Car const& other)
: Model{other.Model}, Something{other.Something}
{}
2nd way:
Car(Car const& other)
{
Model = other.Model;
Something = other.Something;
}
The first version (Constructor Initializer List
) initializes
its data members, whereas the second version assigns
values to the data members.
If data member is not explicitly initialized
in the constructor initializer list, the member is default initialized
before the constructor body starts executing. How significant it is depends on the data member type, therefore, it is good practice to favour first version (Constructor Initializer List
).
Data members that are const
or reference
types must be initialized
. In addition, class
type data members that don't have default constructor must be initialized
too.
The first is calling the copy constructors of the member variables, the second is calling the default constructors of your member variables and then the assignment operator.
To be correct - to implement special member function (constructor/ copy constructor), because only in that methods can be used member initialization syntax(You have mentioned it as 1-st way). It is used for initialization of objects on creation. Second way is used for assignment of values to already created objects, which can be less efficient (especially for complex objects)
The big difference between the two constructors is that the first form will work even if your Model
and Something
members are declared const
or as &
(references). The second form only works if they are not const
or references. Also if you use the second form and they have default constructors, those will get run too, so you are essentially constructing them an unnecessary extra time.
For that reason, I generally prefer to use the first form, if reasonably possible.