There are multiple objects in the subclass, (1) when constructing the subclass object, the sequence of constructor calls; (2) when the program execution ends, the sequence of destructor calls

#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:
insert image description here
After pressing any key:
insert image description here
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!

Guess you like

Origin blog.csdn.net/weixin_46060711/article/details/123932542