-1

If we have:

public:
   MyClass(const std::string& my_str);
private:
  std::string _myStr

In the implementation:

MyClass::MyClass(const std::string& my_str):
   _mystr(my_str)

vs

MyClass::MyClass(const std::string& my_str){
   _mystr = my_str
}

Why is the first version preferred over second?

user1008636
  • 2,989
  • 11
  • 31
  • 45
  • @user17732522 sorry updated question to mean the 2nd version having the assignment inside the body of the constructor – user1008636 May 19 '22 at 04:03

2 Answers2

2

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:

  1. _mystr will be default initialized before the body of the ctor is entered.

  2. 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?.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Are you implying anything specific with the link at the end? The use of `_mystr`/`_myStr` is fine as a class member and it is not uncommon to use a leading underscore (followed by lower case letter) to indicate a private member. – user17732522 May 19 '22 at 04:24
  • @user17732522 No in this case the usage is fine, but i have seen beginners extending this usage of leading underscore to variables that are not a class member and when i ask them about that they seem to assume that that should also work since it works for a class member. So i thought that it would be better to atleast give a link where the OP gets aware of this. – Jason May 19 '22 at 04:27
1

Using a copy constructor expresses your intent more clearly. If you did an assignment instead (in the body of the constructor, not the initialization list) you'd be initializing the member twice, once to its default value and then finally to the value you wanted it to have.

For some members, such as references, you really don't have a choice.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622