lundi 11 octobre 2021

C++: Is value initialisation apply recursively?

I have the below codes:

#include <iostream>
using namespace std;

class X { 
        public:
//              X() {}
                int getX() const { return this -> x; }
        private:
                int x; // <-- Tag 3
};

class Y { 
        public:
//              Y() {}
                int getX() const { return this -> x.getX(); }
        private:
                X x; // <-- Tag 2 value or default initialisation?
};

int main() {
        X x{};
        cout << x.getX() << endl;

        Y y{}; // <-- Tag 1 - value initialisation
        cout << y.getX() << endl;
}

Results:

0
0

Question:

  1. Is Tag 2 value or default initialisation?
  2. If Tag 2 is value initialised then Tag 3 be 0 since Class X will use the synthesized ctor. This seems to be the case since it produce 0.

Also on another note, the compilation shows data members are all initialised.

$ g++ -std=c++11 -Wuninitialized -O2 -pedantic-errors -o a.o a.cc
$ 

Any help would be great!

Aucun commentaire:

Enregistrer un commentaire