c++c++11constructorinitializationin-class-initialization

In-class member initializer using a constructor: is it allowed?


I recently found an interesting piece of code in the article Get to Know the New C++11 Initialization Forms by Danny Kalev:

class C
{
string s("abc");
double d=0;
char * p {nullptr};
int y[5] {1,2,3,4};
public:
C();
};

The line string s("abc"); seems suspicious to me. I thought that using a constructor is not allowed while a member is initialized in-class. And this code (simplified to class C { string s("abc"); };`) doesn't compile with

Am I right and there is an error in this article?


Solution

  • Am I right and there is an error in this article?

    Yes, it is an error in the article.

    Only a brace-or-equal-initializer is allowed in the declaration of a data member. The initializations of d, p, and y are correct, but not s. The rationale for this is that using an expression-list would ambiguate the declaration with a function declaration and it would also cause conflicts with name lookup in the class body.