If a parameter is not specified when you generate an object of the category class after you inherit a category, the default constructor without a parameter is executed, the non-parameter preset constructor of the basic class is also executed. Therefore, based on this feature, some common member States are usually written in the pre-defined constructor, such as setting Some preset values.
If you want to generate an object by using the derivative category after inheritance, specify the parameter when generating the object, and execute a parameter in the Base category to construct the sub-object, you can use: operation sub-
For example:
// Point2D type
Class Point2D {
Public:
Point2D (){
_ X = 0;
_ Y = 0;
}
Point2D (int x, int y): _ x (x), _ y (y ){
}
Private:
Int _ x;
Int _ y;
};
// Point3D category
Class Point3D: public Point2D {// inherits the Point2D class
Public:
Point3D (){
_ Z = 0;
}
// Construct the form and specify the parent class of the call.
Point3D (int x, int y, int z): Point2D (x, y), _ z (z ){
}
Private:
Int _ z; // Add private data
};
If you use a derivative class to generate an object, the execution sequence of the constructor class starts from the constructor class. This is understandable because the base class is the basis of the category class, some basic parameters or initial states must be completed first, and then the constructor in the derivative category must be completed.
When an object is destroyed, the execute sequence of the deconstruct function is the opposite. It starts execution from the deconstruct class, and then comes the basic class constructor, if the deconstruct function of the Base category is executed first, some States of derived classes dependent on the Base category will also be reconstructed (such as indicators). Then, the deconstruct function of the Base category will be executed again, errors may occur due to dependency issues.
The following simple program tells you how to construct and deconstruct the correspondence, and the execution sequence after inheritance:
# Include Using namespace std; class Foo1 {public:
Foo1 (){
Cout <"Foo1 constructor" <endl;
}
~ Foo1 ()
{
Cout <"Foo1 deconstruct function" <endl;
}
};
Class Foo2: public Foo1 {public:
Foo2 (){
Cout <"Foo2 constructor" <endl;
}
~ Foo2 (){
Cout <"Foo2 deconstruct function" <endl;
}
};
Int main ()
{
Foo2 f;
Cout <endl;
Return 0;
}
Execution result:
Foo1 Constructor
Foo2 Constructor
Foo2 deconstruct
Foo1 deconstruct