There are two methods to initialize member variables in the C ++ class:
ConstructorInitialization listAnd constructor bodyAssign values.Let's take a look at the differences between the two methods.
The initialization sequence of member variables is defined in that order.
1Internal data type (char, Int...... Pointer, etc)
ClassAnimal
{
Public:
Animal (IntWeight,IntHeight )://A Initialization list
M_weight (weight ),
M_height (height)
{
}
Animal (IntWeight,IntHeight)//Function B Initialization
{
M_weight = weight;
M_height = height;
}
Private:
IntM_weight;
IntM_height;
};
For these internal types, there is basically no difference in efficiency.
Of course, a and B cannot coexist.
2There is no default constructor in the inheritance relationship
ClassAnimal
{
Public:
Animal (IntWeight,IntHeight )://No constructor provided
M_weight (weight ),
M_height (height)
{
}
Private:
IntM_weight;
IntM_height;
};
ClassDog:PublicAnimal
{
Public:
Dog (IntWeight,IntHeight,IntType)//The parent class of the error constructor animal does not have an appropriate constructor.
{
}
Private:
IntM_type;
};
The initialization of the parent class must be provided in the constructor of the derived class, because the object construction order is:
Parent class -- subclass --......
So it must:
ClassDog:PublicAnimal
{
Public:
Dog (IntWeight,IntHeight,IntType ):
Animal (weight, height)//You must use the initialization list to add initialization for the parent class.
{
;
}
Private:
IntM_type;
};
3ConstConstant. It must be initialized in the initialization list and cannot be initialized using a value assignment.
ClassDog:PublicAnimal
{
Public:
Dog (IntWeight,IntHeight,IntType ):
Animal (weight, height ),
Legs (4)//Must be initialized in the initialization list
{
//Legs = 4;//Error
}
Private:
IntM_type;
Const IntLegs;
};
4. initialize a member that contains a custom data type (class) object
ClassFood
{
Public:
Food (IntType =10)
{
M_type =10;
}
Food (Food & other)//Copy constructor
{
M_type = Other. m_type;
}
Food &Operator= (Food & other)//Overload assignment = Function
{
M_type = Other. m_type;
Return*This;
}
Private:
IntM_type;
};
(1) The constructor assigns a value to initialize the member object m_food.
ClassDog:PublicAnimal
{
Public:
Dog (Food & Food)
//: M_food (food)
{
M_food = food;//Initialize a member object
}
Private:
Food m_food;
};
//Use
Food FD;
Dog dog (FD );//
Result:
First, the Object Type constructor food (IntType =10) -->
Then, execute the Object Type constructor Food &Operator= (Food & other)
Imagine why?
(2) Constructor initialization list
ClassDog:PublicAnimal
{
Public:
Dog (Food & Food)
: M_food (food)//Initialize a member object
{
//M_food = food;
}
Private:
Food m_food;
};
//Use
Food FD;
Dog dog (FD );//
Result: The food (Food & Other) copy constructor is executed to complete initialization.
Different initialization methods have different results:
Obviously, the method of constructing the function initialization list is more efficient.