全部博文(26)
分类: C/C++
2010-11-09 22:28:27
Constructor Initialization list
As we all known,we can initial our class member data in the constructor using the assignment operator.For example:
|
When the class's constructo is executed, the class member a and b are created. Then the body of the constructor is run, where the member data variable are assigned values. Attention, they are non-const variable, and pointer variable is ok.
Well,did you ever think about what would happen when we use const or reference variables as the class member? You should know that the const and reference variables must be initialized on the line as they are declared. I mean:
|
So We can't use it in the constructor as follows:
|
Thus, we need another way to initialize them as they are declared. And this is done through using of an initialization list, which allows us to initialize member variables when they are created rather than afterwards.
Using an initialization list is very similar to doing implicit assignments.For instance:
|
The initialization list is inserted after the constructor parameters, begin with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma(,), Note that we no longer need to do the explicit assignments in the constructor body,since the initializer list replace that functionality. Also note that the initialization list doed not end in a semicolon (;).
Ok...Now you have already known the initialization list. There comes another question:
Are the class member variables initialized in accordence with the order of the initialization list?
Well..I supposed you to run the two programs showing as follow on your computer, and then you'll understand that...
Example 1:
|
Example 2:
|
Example 1's run results:
14122996 //a random integer
1
Example 2's run results:
1
1
As the runing results showed: we can know that the class member variables initialized in accordence with the order of being declared in the class, but not the order of initialization list showing.
Did you get it?