Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Initializing a std::string member

Tags:

c++11

When I initialize the std::string member of a class calling its C string constructor, I receive the following errors:

error: expected identifier before string constant
error: expected ',' or '...' before string constant

Although, the program compiles successfully when I use copy initialization or list initialization.

class Element
{
private:
    std::string sName_("RandomName"); // Compile error
    std::string sName_ = "RandomName"; // OK
    std::string sName_{"RandomName"}; // OK
}

What seems to be the problem?

UPDATE

Now I realize this is a stupid question, because, as @p512 says, the compiler will see it as a erroneous method declaration. But I think this question should remain for other people that will do the same thinking error.

like image 404
Alexandru Irimiea Avatar asked Oct 19 '25 12:10

Alexandru Irimiea


1 Answers

std::string sName_("RandomName");

This is an erroneous function declaration - at least that's what the compiler makes of it. Instead you can use something like this:

std::string sName_ = std::string("RandomName");

You can also use initializer lists in the constructor of your class:

class A {
public:
    A() : sName_("RandomName") {}
    std::string sName_;
};

You can find more on that here: http://en.cppreference.com/w/cpp/language/initializer_list

like image 186
cisnjxqu Avatar answered Oct 22 '25 05:10

cisnjxqu