The third week of learning: member objects and closed classes

  1. A class with member objects is called a closed class, which is another class object
  2. Any statement that generates a closed class object must let the compiler understand how the member objects of the object are initialized. The method is to initialize the list.
Execution order of closed class constructor and destructor
  1. For object generation, the constructors of all object members are executed first, and then the closed class constructor is executed last. For example, cars, tires, and engines. You have to have tires and engines first, and then car.
  2. The order in which the constructors of the object members are called has nothing to do with the order of appearance in the initialization list.
  3. When the object dies, the destructor of the enclosing class is called first, followed by the rest of the object members. For example, there are houses, human beings, and there is an earthquake, and you have to collapse the house first, and then the talent is gone. (Actually, the constructor and destructor are access order issues...)
class son1
{
    
    
	public:
		son1() {
    
    cout<<"son1's constructor called\n";}
		~son1() {
    
    cout<<"son1's destructor called\n";}
 }; 
 
 class son2
 {
    
    
 	public:
		son2() {
    
    cout<<"son2's constructor called\n";}
		~son2() {
    
    cout<<"son2's destructor called\n";}
 };
 
 class father
 {
    
    
 	private:
 		son1 s1;
 		son2 s2;
 	public:
 		father() {
    
    cout<<"Father's constructor called\n";}
 		~father() {
    
    cout<<"Father's destructor called\n";}
 };

Call father result:
Insert picture description here

Closed class copy constructor
class A
{
    
    
	public:
		A() {
    
    cout<<"default\n";	}
		A(A& a) {
    
    cout<<"copy\n";}
};

class B
{
    
    
	A a; 
};

int main()
{
    
    
	B b1,b2(b1);
	return 0;
}

Output
default
copy
analysis: First, the default constructor of B is called, and then the default constructor of A is also called. The second is to call the copy constructor of B, and then how can b2.a be copied from b1.a? Call the copy constructor of A.

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108557079