c++constructorinitializer-liststdstringraii

Do objects part of a class not get constructed until its constructor is called


For this simple classes below. For MyClass, the constructor initializes str with s during construction using the intializer list.

Does this mean that str doesn't get constructed at all yet until mc does?

What about in the case for MyClass2 and mc2?

#include <string>

class MyClass
{
    public:
        MyClass(std::string s): str(s){}
     
    private:
        std::string str;
};

class MyClass2
{
    public:
        MyClass2(std::string s){str = s;}
     
    private:
        std::string str;
};

int main()
{
     std::string s = "Hello";
     MyClass mc(s); 
     MyClass2 mc2(s); 
}

Solution

  • All member constructions happen between the ":" and the "{". Once you enter inside the {...} scope, everything has already been constructed.

    So in your first example, str(s) is actually a call to the copy-constructor of std::string.

    In the second example, construction still happens there, but because you didn't specify anything, string's default constructor is called. In string's particular case, that means it is initialized to the empty string. Once you enter the constructor's scope, you are assigning s to str, overwriting the initialization. So a bit of a waste.