Give the conclusion first:
(1) The base class sub-objects and child objects in the derived class must be initialized, initialized in the initialization list of the constructor of the derived class, or, if not initialized in the initialization list, by invoking the default constructor. (2) The order in which the derived class constructors are called: Constructors for base classes Constructors for child object classes Constructors for derived classes
Example
Class Point1 {public:point1 (); point1 (int i); virtual ~point1 ();p rivate: int x; }; Point1::p oint1 () { x=1; cout<< "Point1 ' s default constructor called!\n";} Point1::p oint1 (int i) { x=i; cout<< "Point1 ' s constructor called!\n";} Point1::~point1 () {} class Point2:public point1 {public:point2 (); point2 (int i,int j,int k); virtual ~point2 (); Point1 p;}; Point2::p oint2 () { cout<< "Point2 ' s Defaule constructor called\n";} Point2::p oint2 (int i,int j,int k) {cout<< "Point2 ' constructor called\n";} Point2::~point2 () {} //main function void Main () { point2 pp; Point2 PP1 (a);}
Run results
Point1 ' s default constructor called!//Point1 p; Call the base class default constructor Point1 ' s default constructor called!//point2 ' s Defaule Constructor Calledpoint1 ' s default constructor called!//Point1 p; called the base class default constructor Point1 ' s default constructor called! Point2 ' s constructor called
if the function
Point2::p oint2 (int i,int j,int k) {cout<< "Point2 ' constructor called\n";}
instead:
Point2::p oint2 (int i,int j,int k):p (j) {cout<< "Point2 ' constructor called\n";}
The result of the operation is:
Point1 ' s default constructor called!point1 ' s default constructor Called!point2 ' s Defaule constructor calledpoint1 ' s Default constructor called!point1 ' s constructor Called!point2 ' s constructor called
c++--initialization of child objects and base class objects in an inherited class