1. A hard-to-find problem
See the following code snippet:
ClassTest
{
Public:
Test (IntVal): ref _ (VAL ){}
~ Test (){}
Private:
Int& Ref _;
};
IntMain ()
{
Test T (1 );
Return0;
}
What problem do you see? Maybe nothing.
Yeah, you initialize the test: ref _ by a value of type "int", that's ref _ (VAL)
But if you try directly:
Int& Ref1 = 2; // complier complain!
Why?
Actually, the test: ref _ is initialized in the constructor,Function. That's mean ref _ is initialized by An automaic variable (formal argument Val), not just a literation constant like 2. So that's true at 1st snippet.
But you can't initialize a non-const reference directly by a literation constant in 2nd snippet. Instead, you can do:
Const Int& Ref2 = 3;
Here, a temporary with typeConst intHave been generated, and then this temporary can initializeConst Int &Reference.
Specially, in the following case, an extra type conversion has occured before the initialization:
Const Double& Ref3 = 4;
2. problem again and Improvement
In 1st snippet, the test: ref _ actually refers to an automatic variable, which have been destroyed after constructor invocation. So the approach for initializing the member of reference type is terriblely dangerous!
A possible approach is like this:
ClassTest
{
Public:
Test (Int& Val): ref _ (VAL ){}
~ Test (){}
Private:
Int& Ref _;
};
IntMain ()
{
Test T (1 );
Return0;
}
3. Why must use Member initialization list for reference data member and const data member?
First, you shoshould understand the advantage of member initialization list.
In 3 cases, you must use Member initialization list:
1) object member (no built-in type)
2) const Member
3) Reference Member
Because const and reference type must intialize when declaration (defination), you cannot just declare without initialization them at first, and then initialize them by assignment.
So it's very important to differentiate the distinction between initialization and assignment. At fact, the complier can strictly disguish the difference!
You can try:
ClassTest
{
Public:
Test (CharCh,Int& Val) {CH _ = CH; Ref _ = val ;}
~ Test (){}
Private:
Const CharCH _;
Int& Ref _;
};
IntMain ()
{
IntA = 2;
Test T ('C', );
Return0;
}
This time, the complier will complain some warnings... ah
------
Assignment of read-only data-member 'test: CH _ 'main. cc cpp 4 C/C ++ Problem
Uninitialized member 'test: CH _ 'with 'const 'type' const char 'main. cc cpp 4 C/C ++ Problem
Uninitialized reference member 'test: ref _ 'main. cc cpp 4 C/C ++ Problem
Summary:
1) All the operations in the body of contructor are regarded as assignment but not initialization.
2) reference and const type must be initialized when and only when they are declared (defined, if exactly speaking ).