Member object: the member variable of one class is an object of another class
The class that contains the member object is called the enclosing class (enclosing)
The following code:
classCtyre {Private: intradius; intwidth; Public: Ctyre (intRintW): Radius (r), Width (w) {}//Init list}; classcengine {};classCcar {//Automotive class, closed classPrivate: intPrice ; Ctyre Tyre; Cengine engine; Public: Ccar (intPintTrinttw);}; Ccar::ccar (intPintTrinttw):p rice (p), Tyre (tr, TW) {}intMain () {Ccar car (20000, -,225); return 0;}
If the Ccar class does not define a constructor, then Ccar car; A compilation error will occur
The compiler doesn't know how to initialize Car.tyre
Car.engine initialization is not a problem, use the default constructor
How to initialize a statement, "Member objects in an object", that generates an enclosing class object
When defining a constructor for an enclosing class, add an initialization list:
Class Name:: constructor (Parameter table): member variable 1 (parameter table), member variable 2 (parameter table), ...
{
...
}
Call Order
When the enclosing class object is generated, the
First step: Execute constructors for all member objects
Step Two: Execute the constructor of the enclosing class
constructor invocation order for member objects
1. Consistent with the order in which member objects are described in the class
2. Regardless of the order in which they appear in the member initialization list
When the object of the enclosing class dies,
First step: Execute the destructor of the enclosing class first
Step two: Perform the destructor for the member object
C + + Member objects and enclosing classes