9.2 Initialization table for constructors
Constructors have a special initialization method called "Initialization expression Table" (abbreviated as initialization table). The initialization table is after the function parameter table, but before the function body {}. This means that the initialization of the table occurs before any code in the body of the function is executed.
Constructor initialization table usage rules:
U if a class has an inheritance relationship, the derived class must call the constructor of the base class in its initialization table.
For example
Class A
{...
A (int x); A's constructor
};
Class B:public A
{...
b (int x, int y);//B's constructor
};
B::B (int x, int y)
: A (x)///The constructor of a is called in the initialization table
{
...
}
The const constant of the U class can only be initialized in the initialization table because it cannot be initialized in the function body by assignment (see section 5.4).
The initialization of a data member of the U class can be two ways in which the initialization table or function body is assigned, and the efficiency of the two methods is not exactly the same.
Member objects of non-intrinsic data types should be initialized in the first way to achieve greater efficiency. For example
Class A
{...
A (void); Parameterless constructors
A (const a &other); Copy Constructors
A & operate = (const a &other); Assignment function
};
Class B
{
Public
B (const A &a); B's Constructor
Private
A M_a; Member objects
};
In Example 9-2 (a), the constructor of Class B invokes the copy constructor of Class A in its initialization table, thus initializing the member object m_a.
In the example 9-2 (b), the constructor of Class B initializes the member object M_a in the body of the function by assigning a value. All we see is an assignment statement, but actually the constructor for B does two things: Create the M_a object secretly (call a parameterless constructor), call the assignment function of Class A, and assign the parameter A to m_a.
B::B (const A &a)
: M_a (a)
{
...
}
B::B (const A &a)
{
M_a = A;
...
}
Example 9-2 (a) member object initialized in initialization table 9-2 (b) member object is initialized in the function body
The efficiency of the two initialization methods is almost indistinguishable for data members of internal data types, but the latter's program layout seems clearer. If the Declaration of class F is as follows:
Class F
{
Public
F (int x, int y); Constructors
Private
int m_x, m_y;
int m_i, M_j;
}
The constructor for F in Example 9-2 (c) takes the first initialization, and the constructor for F in Example 9-2 (d) takes a second initialization.
F::f (int x, int y)
: m_x (x), m_y (y)
{
m_i = 0;
M_j = 0;
}
F::f (int x, int y)
{
m_x = x;
m_y = y;
m_i = 0;
M_j = 0;
}
Example 9-2 (c) data members are initialized in the initialization table 9-2 (d) data members are initialized in the function body