#include <iostream>
using namespace std;
class M {
public:
M() {
cout << __FUNCTION__ << endl; }
~M() {
cout << __FUNCTION__ << endl; }
};
class N {
public:
N() {
cout << __FUNCTION__ << endl; }
~N() {
cout << __FUNCTION__ << endl; }
};
class A {
public:
A() {
cout << __FUNCTION__ << endl; }
~A() {
cout << __FUNCTION__ << endl; }
};
class B : public A {
public:
B() {
cout << __FUNCTION__ << endl; }
~B() {
cout << __FUNCTION__ << endl; }
private:
M m1;
M m2;
static N ms;
};
N B::ms;
int main(void) {
{
B b;
printf("\n\n*************\n\n");
B c;
printf("\n\n*************\n\n");
}
system("pause");
return 0;
}
The output is:
After pressing any key:
1. When creating a subclass object, the calling order of the constructor:
the constructor of the static data member -> the constructor of the parent class -> the constructor of the non-static data member -> its own constructor Note: No matter how
many
objects are created, the static member of the class is only constructed once, so the constructor of the static member is only called once!!!
2. The calling order of the destructor of the subclass is opposite to that of the constructor of the subclass! ! !
Remember, do the opposite.
3. The static object is destroyed when the program terminates, so:
the destructor of the static member will not be called before the end of the program!