If you inherit a category, if you do not specify a parameter when you generate an object of a derived class, a preset constructor without parameters is executed, and a parameterless preset constructor for the underlying class is also executed, so based on this feature, it is common for a preset constructor to compose some generic Member State initial, such as setting some preset values.
If you inherit, you want to use the derived class to build the object, specify the parameters when you build the object, and simultaneously perform a parameter constructor in the base class, you can use: operator
For example:
POINT2D category
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 {//Inheritance point2d category
Public
Point3D () {
_z = 0;
}
constructors, specifying call parent class constructors
Point3D (int x, int y, int z): point2d (x, y), _z (z) {
}
Private
int _z; New private information
};
If you use a derived class to generate an object, it is understandable that the execution order of the constructors starts with the constructor of the base class, since the base class is the basis for the derived class, and some of the underlying parameters or initial states must be completed before the constructor in the derived class is completed.
When an object is eliminated, the order in which the destructor is executed is the exact opposite. is to start with the destructor of the derived class, and then the constructor for the underlying class, because if the destructor of the base class is executed first, some states of the derived class that are dependent on the base class are also refactored (for example, the metric). Then the destructor of the derived class will have a dependency problem and cause an error.
Here's a simple program that tells you the constructors and deconstruction functions, and the order of execution after inheritance:
#include using namespace std; Class Foo1 {public:
Foo1 () {
cout << "Foo1 constructor" << Endl;
}
~foo1 ()
{
cout << "Foo1 deconstruction function" << Endl;
}
};
Class Foo2:public Foo1 {public:
Foo2 () {
cout << "Foo2 constructor" << Endl;
}
~foo2 () {
cout << "Foo2 deconstruction function" << Endl;
}
};
int main ()
{
Foo2 F;
cout << Endl;
return 0;
}
Execution results:
Foo1 constructs the function type
Foo2 constructs the function type
Foo2-Deconstruction function
Foo1-Deconstruction function