1. Order
Call the constructor of the base class first, and then call the derived class constructor. The destructor sequence is reversed.
2. Constructors
Derived classes call the base class constructor--The default constructor of the base class without initializing the list
Derived classes call base class with parameter constructor, call base class with parameter constructors associated with the initialization list
If a derived class has more than one constructor version, any one of the base class constructors does not match, an error occurs.
3. Copy Constructors
The derived class does not define a copy constructor, call the base class's copy constructor (if any) or the default copy constructor, and the default copy constructor of the derived class
A derived class defines a copy constructor that does not use the initialization list to call the base class copy constructor, call the base class default constructor
A derived class defines a copy constructor that uses the initialization list to call the base class copy constructor, call the base class copy constructor, if any, or the default copy constructor
Example:
#include <iostream>using namespacestd;classa{ Public: A () {cout<<"A Default constructor"<<Endl; } A (inti) {cout<<"a A (int i) constructor"<<Endl; } ~A () {cout<<"A destructor"<<Endl; } A (ConstA &obj) {cout<<"A Copy Constructor"<<Endl; }};classD | Publica{ Public: B () {cout<<"B Default constructor"<<Endl; } B (intj): A (j) {cout<<"b b (int J): A (j)"<<Endl; } ~B () {cout<<"B destructor"<<Endl; } B (ConstB & obj)//call A's default constructor{cout<<"B Copy Constructor"<<Endl; } //B (const B & obj): A ()//call A's default constructor//{ //cout << "B copy constructors" << Endl; //} //B (const B & obj): A (obj)//call A's copy constructor//{ //cout << "B copy constructors" << Endl; //}};intMain () {{cout<<"----------------------"<<Endl; b b; cout<<"----------------------"<<Endl; B B1 (3); cout<<"----------------------"<<Endl; b B2 (b); cout<<"----------------------"<<Endl; } return 0;}
Constructors and destructors when "C + +" inherits