Wason
Wason

Reputation: 1493

Can const member be initialized in c++ construtor?

I read code snippet here. Please search "Const class Data members" to get to the section. Code is like below:

class Test
{
   const int i;
   public:
   Test (int x)
   {
     i=x;
   }
};

int main()
{
 Test t(10);
 Test s(20);
}

I use VS2013 warning me it's not correct. As I know, const member variables can only be initialized by an initializing list. Sth. like:

Test (int x):i(x){}

Did the newer C++ standard update to support that(If so, the change sounds reasonable, initializing in function body seems no difference, right?)? Or the document make a mistake(I presume it won't make such mistake).

Upvotes: 1

Views: 84

Answers (2)

songyuanyao
songyuanyao

Reputation: 172954

The rule didn't change (from C++98).

Note that i=x; inside the constructor's body is not initialization but assignment; they are different things. For const members, they can only be initialized,

For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

e.g. Test (int x):i(x){},

but they cannot be assigned,

Test (int x)
{
  i=x;  // assignment is not allowed
  ...
  i=42; // assignment again; that makes no sense for const at all
}

Upvotes: 2

Hatted Rooster
Hatted Rooster

Reputation: 36503

Yes, const members can only be initialized (by using an initialization list) and not assigned to, as is shown in your code snippet. No, newer C++ standards have not updated this to support assignment in the constructor.

The tutorial in question that contains that code snippet is wrong. I'd advise against reading such tutorials as they more often than not have subtle (and not-so-subtle) errors in them.

Upvotes: 0

Related Questions