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
-std=c++11 -Wall -Wextra -Werror -pedantic-errors
)-std=c++11 -Wall -Wextra -Werror -pedantic-errors
)/EHsc /Wall /wd4514 /wd4710 /wd4820 /WX /Za
)/EHsc /nologo /W4 /c
)Am I right and there is an error in this article?
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.