Why could const member be initialized twice?

  • A+

Below is a code snippet which could be compiled and run without error in vs2015

#include<iostream> using namespace std;  class A {     public:         A(int b) :k(b) {}//second time     const int k = 666;//first time };  int main() {     A a(555);     cout << a.k << endl;     return 0; } 

The output is 555. But as far as I know,const object should be initialized only once,after which the value is unmodifiable.

It's not initialized twice; the default member initializer is just ignored. So for A a(555);, a.k is initialized as 555.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.

On the other hand, given

class A { public:     A() {}            // k will be initialized via default member initializer, i.e. 666     A(int b) :k(b) {} // k will be initialized via member initializer list, i.e. b      const int k = 666; }; 

then for A a;, a.k will be initialized as 666.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: