jeudi 3 mai 2018

Why could const member be initialized twice?

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 unchageable.

Aucun commentaire:

Enregistrer un commentaire