Why is the first version preferred over second?
The first version initializes the data member while the second version assignes a value to it.
The second version has an overhead because, in the second case the data member _mystr
will first be default initialized before the body of the constructor is entered and then inside the body of the ctor it will be assigned a value(using _mystr = my_str
). So in the second case there are 2 steps involved:
_mystr
will be default initialized before the body of the ctor is entered.
Next, inside the body of the ctor , the assignment _mystr = my_str
will happen.
Note that initialization and assignment are different things in C++.
Version 1
//-------------------------------------------vvvvvvvvvvvvv--->INITIALIZATION of data member myStr
MyClass::MyClass(const std::string& my_str): myStr(my_str)
{
//no ASSIGNMENT happening here
}
Version 2
MyClass::MyClass(const std::string& my_str)//before the body of this ctor is entered, myStr will be default initialized
{
myStr = my_str; //ASSIGNMENT happening here
}
Also, take a look at What are the rules about using an underscore in a C++ identifier?.