user34537
user34537

Reputation:

Why specifying the default value outside of a class is allowed but not inside it?

#include <atomic>
std::atomic<int> outside(1);
class A{
  std::atomic<int> inside(1);  // <--- why not allowed ?
};

error:

prog.cpp:4:25: error: expected identifier before numeric constant
prog.cpp:4:25: error: expected ',' or '...' before numeric constant

In VS11

C2059: syntax error : 'constant'

Upvotes: 5

Views: 1302

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507045

In-class initializers do not support the (e) syntax of initialization because the committee members that designed it worried about potential ambiguities (For example, the well-known T t(X()); declaration would be ambiguous and does not specify an initialization but declares a function with an unnamed parameter).

You can say

class A{
    std::atomic<int> inside{1};
};

Alternatively a default value can be passed in the constructor

class A {
  A():inside(1) {}
  std::atomic<int> inside;
};

Upvotes: 8

Related Questions