22.9 Parent and child constructors and destructors

When a class object is constructed, the following sequence takes place.

  1. Memory storage for the object is allocated (e.g. enough bytes for the object's data fields are allocated in memory).

  2. The default constructor of the parent class (if any) is called, unless you explicitly request some other parent constructor in your initializer list.

  3. The constructors for each of the class member objects are executed (in the order of the member classes' declaration); if there is no initializer list the default constructors are called, but you can request special constructors in your initializer list.

  4. The class constructor code is executed.

When a class object is destroyed the following sequence takes place.

  1. The class destructor code is called.

  2. The destructor of each of the class member objects is executed.

  3. The destructor of the base class (if any) is executed.

  4. The memory storage for the object is recycled.

So the cMyChild constructor automatically calls the default cMyParent constructor before getting inside its own code. A handy way to think of this is to imagine that a cMyChild object has a cMyParent object as a member. The parent class and the members all get their constructors called.

Now, it may be that you want to feed some arguments into the base class or member constructors. To do this, you write out these constructors in an 'initializer list' that follows a colon after the constructor. Here's an example of a class definition.

cTeacherProgrammer : public cProgrammer 
    int _ugliness; 
    cGollywog *_pimaginaryfriend; 
    cTeacherProgrammer(int flubba, float gleep); 

And here's a constructor using an initializer list.

cTeacherProgrammer::cTeacherProgrammer(int flubba, float gleep): 
    cProgrammer(flubba, gleep), 
    _pimaginaryfriend = new cGollywog(this); 

And here's how the destructor would be defined.

cTeacherProgrammer::~cTeacherProgrammer(){delete _pimaginaryfriend);} 

Note that the cTeacherProgrammer destructor first does the delete _pimaginaryfriend, and then calls the parent cProgrammer destructor. You can remember the sequence by thinking in terms of working your way down the hierarchy at construction, and working your way back up at destruction.

When you need to code up several different forms of a constructor, it can be useful to have an initialization helper function that the different constructors in both the parent and the child class can call.

    Part I: Software Engineering and Computer Games
    Part II: Software Engineering and Computer Games Reference