lundi 23 avril 2018

C++11 order of member class initialization

I have code:

struct testInit {
    testInit(int i1_) 
        : i1(i1_) {
        std::cout << "testInit::testInit" << std::endl;
    }

    int initI2() {
        std::cout << "testInit::initI2::i1: " << i1 << std::endl;
        return i1;
    }

    const int i1 = 1;
    const int i2 = initI2();

};

int main() {
    testInit ti(3);

    std::cout << "i1: " << ti.i1 << std::endl;
    std::cout << "i2: " << ti.i2 << std::endl;

    return 0;
}

The output is:

testInit::initI2::i1: 3
testInit::testInit
i1: 3
i2: 3

So, I am wondering what exactly is order of initialization of class members. I thought that the output should be i1: 3 and i2: 1 - what is oblivious wrong - but why?

Aucun commentaire:

Enregistrer un commentaire