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.
From the standard, [class.base.init]/10:
If a given non-static data member has both a default member initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member's default member initializer is ignored. [ Example: Given
struct A { int i = /* some integer expression with side effects */ ; A(int arg) : i(arg) { } // ... };the
A(int)constructor will simply initializeito the value ofarg, and the side effects ini's default member initializer will not take place. — end example ]
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.
It is initialized only once.
const int k = 666; would be used if not provided in constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With