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.