C++ object creation process

The creation of objects is roughly divided into three stages

  1. Execute the constructor of the base class
  2. Execute the constructor of the class type member
  3. Execute the constructor of your own class

  1. Execute the base class constructor of the class
    • All base classes will execute their own constructor, regardless of whether the base class is in the initialization list or not.
    • The constructor can be specified in the initial speech list, if not specified. Just call the default constructor.
    • Execution order, press, declare the writing order of the base class when inheriting. It has nothing to do with the order in the initialization list.
  1. Initialize the class type members of the class
    • All class type members will call the constructor to initialize themselves, regardless of whether the member is in the initialization list.
    • The constructor can be specified in the initial speech list, if not specified. Just call the default constructor.
    • Execution order, press, the writing order of the members when declaring the class. It has nothing to do with the order in the initialization list.
  1. Execute the class's own constructor

demo:


#include<bits/stdc++.h>
using namespace std;

class Parent2 {
    
    
public:
    Parent2() {
    
    
        cout << "Parent2 constructor is called\n";
    }
};

class Parent1 {
    
    
public:
    Parent1() {
    
    
        cout << "Parent1 constructor is called\n";
    }
};

class A {
    
    
public:
    A() {
    
     cout << "A constructor is called\n"; }
};

class B {
    
    
public:
    B() {
    
     cout << "B constructor is called\n"; }
};

class Son : Parent1 , Parent2
{
    
    
    A a;
    B b;
public:
    Son(): b(), Parent1()
    {
    
    
        cout << "Son constructor is callede\n";
    }
};

int main()
{
    
    

    Son s;
    return 0;
}

Results of the:

Parent1 constructor is called
Parent2 constructor is called
A constructor is called
B constructor is called
Son constructor is callede

Guess you like

Origin blog.csdn.net/wx_assa/article/details/107842163