Reprinted from: http://www.cnblogs.com/lidabo/p/3790606.html, thanks to the author!
Source of the problem:
As a result of the interview problem, the examiner out a simple program output value of the problem: as follows,
- Class A
- {
- Private
- int N1;
- int n2;
- Public
- A (): n2 (0), N1 (n2+2) {}
- void Print () {
- cout << "N1:" << N1 << "n2:" << n2 <<endl;
- }
- };
- int main ()
- {
- A;
- A.print ();
- return 1;
- }
At this point, the candidate replied: N1 is 2,n2 is 0.
In My Computer output results are:
If you answer the same question, you certainly don't understand the order in which the member lists are initialized.
If I change the constructor in Class A to:
- A ()
- {
- N2 = 0;
- N1 = N2 +2;
- }
At this point the output results are:
Analysis:
1. member variables are independent of the order in which the list of members is initialized in the constructor when initialized with the initialization list, only in relation to the order in which the member variables are defined. Because the order in which member variables are initialized is based on the variables in the in-memory order, the in-memory order is determined as long as the compilation period is based on the order in which the variables are defined. This is described in detail in the effectivec++.
2. If initialization is not initialized with initialization list, it is related to the position of the member variable in the constructor when initializing within the constructor.
3. Note: Class members are not initialized when they are defined
4. Note: Const member constants in a class must be initialized in the constructor initialization list.
5. Note: Static member variables in a class must be initialized outside of the class.
6, static variables are initialized &NBSP;&NBSP;
- The member variable definition for BBB:
- Private
- BBB's constructor:
- BBB::BBB ()
- : N2 (1),
- N1 (2)
- {
- }
- Assembly Code:
- 00401535 mov eax,dword ptr [ebp-4]
- 00401538 mov dword ptr [eax+4],2
- 0040153F mov ecx,dword ptr [ebp-4]
- 00401542 mov dword ptr [ecx+8],1
- The member functions of the derived class are then initialized according to the derived chain.
. Summary: Variables ofthe order of initialization should be:
- 1 static variables or global variables of a base class
- 2 static variables or global variables for derived classes
- 3 member variables of the base class
- 4 member variables for derived classes
Initialization order issues for C + + member variables