jefftime
jefftime

Reputation: 440

Direct Initialization vs. Value Initialization

I am a C programmer trying to learn C++11, and I've run into something I don't understand. From what I can tell, the following issue is a difference between value initialization and direct initialization.

The following code snippet does not compile using Visual Studio:

class TestClass {
    int _val;
    std::string _msg;
public:
    TestClass(int, std::string);
    void action();
};

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg{msg}
{
}

void TestClass::action()
{
    std::cout << _msg << _val << std::endl;
}

It gives me:

error C2797: 'TestClass::_msg': list initialization inside member initializer list or non-static data member initializer is not implemented

However, changing

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg{msg}

to

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg(msg)

fixes my problem. What is the difference between these two forms of initialization, and when should one be used over the other? I've been led to believe that I should use value initialization whenever dealing with explicit types.

Upvotes: 2

Views: 683

Answers (1)

Nasser Al-Shawwa
Nasser Al-Shawwa

Reputation: 3653

This is an implementation detail of the Visual C++ compiler. You can read more about this error here. The page states:

The C++ compiler in Visual Studio does not implement list initialization inside either a member initializer list or a non-static data member initializer

Your code attempts to implement the first case. The solution you proposed solves this problem, but if you still prefer to use the initializer list somehow in the constructor, you can do this:

TestClass::TestClass(int val, std::string msg)
    : _val{val}, _msg(std::string{msg})

Which will work as you intend.

Upvotes: 3

Related Questions