I am trying to understand how classes are compiled in C++. And so creating different examples to understand initialization rules (along with theory from books). My example code is as follows:
#include <iostream>
using namespace std;
class NAME {
public:
NAME(int p) : x(r) {
cout << x << endl;
}
int &x;
int r=3;
};
int main() {
NAME obj(4);
return 0;
}
My question is that does the order in which I have specified the data members &x and int r=3 matter? I have checked by reversing the order of those two and still the program works. I have read that compilation of classes happens in two steps:
- All member declarations are compiled.
- Then function bodies are complied.
Now my question is according to this rule the declarations of reference type x should happened first (since compilation happens in order of variable declaration/definition) and then int type r should happen. And then constructor bodies should be compiled. But since we must always initialize a reference type, how is this program working when we have not initialized x? Also, I know that constructor initializer list are used to initialize x from r. I think I am getting confused about the fact that when using the initializer list, will the in-class declaration happen first or will the constructor list directly initialize the members? If it is the latter then why does the order of arguments in the initializer list matter?
PS: I know we have initialized x through the initializer list x(r) but what happens to the in-class definitions/declarations of x and r? Will they be ignored when a initializer list is present? And in what order does all this happens?