The C ++ constructor has three tasks:
1. Allocate space.
2. initialize members.
3. Execute the initialization function body.
To improve efficiency and other reasons, an initialization list is introduced. The call to the initialization list is called before the function body is executed. It is often used for class combination and class inheritance, it can only be used for constructor and copy constructor. How to Use the constructor initialization list in C ++:
Derived class name: name of the derived class (base class 1 parameter, base class 2 parameter ,... base Class N-shaped parameters, this class-shaped parameters): Base Class 1 (parameter), base class 2 (parameter ),... base Class N (parameter), object data member Initialization
{
The initial value statement assigned to the class members;
}
The usage of the constructor initialization list in C ++:
1. When a class relationship is a combination, the constructor is called implicitly for the object as a member to generate a famous object. In this case, the initialization list passes real parameters for the constructor.
2. When the class relationship is inherited, the constructor is explicitly called for the parent class members that are part of the subclass to generate an unknown object. The initialization list also passes real parameters for the constructor.
3. You can also assign an initial value to the data member of the class. It is especially used for the initialization of "regular data members" and "referenced data members. The reason is: const prevents misassignment. The reference type must be defined and assigned together.
Benefits of using the initialization list:
1. PASS Parameters for the initialization base class so that they can have parameters to initialize the base class.
2. Improve the initialization efficiency of composite Members. Because the initialization list is equivalent to placing the composite member in the constructor for initialization, the value assignment constructor that calls the composite member object is omitted, the temporary objects generated by explicitly calling the constructor of the composite Members are also omitted.
Example:
Class base
{
Public:
Base (int I );
};
Base: Base (int I)
{
}
Class
{
Public:
A (base I );
PRIVATE:
Base & RB;
Const base CB;
};
A: A (Base B): Rb (B), CB (B)
{
}