Hi 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 compilaion 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 happend first(since compilation hppens in order of variable declartion/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 intialize 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 we use initializer list then will the in-class declaration will happen first or the constructor list will directly initialize the members? ** If it is the latter then why does the order of arguments in the initializer list matters?
Aucun commentaire:
Enregistrer un commentaire