29.7 Serializing child classes

If you have a child class of an existing class with a Serialize method, you will in fact inherit a serviceable Serialize method. And if you have put the correct DECLARE_SERIAL macro in your *.h and IMPLEMENT_SERIAL in your *.cpp, the inherited Serialize code will save and load the right kinds of child class objects.

If your child class has some new members then you need to override the Serialize method by adding this line to the class declaration: virtualvoid Serialize(CArchive& ar), and by then implementing the method in the code.

For instance our cCritterBullet class includes a new _hitstrength field, and a few other things, so we override its Serialize method to save and load this data. When overriding a Serialize method, you always call the parent class's Serialize method at the start of the code block like this.

void cCritterBullet::Serialize(CArchive &ar) 
    if (ar.IsStoring()) //Writing data. 
        if(_pownerbiota && _pshooter) 
            _shooterindex = _pownerbiota->_index(_pshooter); 
        ar << _hitstrength << _dieatedges << _shooterindex; 
    else //reading data 
        ar >> _hitstrength >> _dieatedges >> _shooterindex; 
        _pshooter = NULL; //Gets fixed by the cBiota call to 

Let's look at the relevant fixPointerRefs here, too.

void cCritterBullet::fixPointerRefs() 
    if (_pownerbiota) 
        _pshooter = 

As another example, cGamePicknpop uses two cRealBox rectangles, so we save and load them.

void cGamePickNPop::Serialize(CArchive &ar) 
    if (ar.IsStoring()) //Writing data. 
        ar << _packingbox << _targetbox; 
    else //Reading data. 
        ar >> _packingbox >> _targetbox; 

It's really easy to mess up your Serialize code, and when you do, it's hard to debug it. The most common error is to fail to save and then load things in the same order. If this happens then, when you load, a lot of variables end up with garbage in them and the program crashes in some (usually) unenlightening way. When you have broken serialization code, the best practice is to back up to a point where it works, and then begin adding in the code bit by bit, being really obsessive about making things match.

One thing to keep in mind when testing your Serialize code is that the default MDI behavior is to not open a given file if a file of the same name is already open. So if you have saved a file as test.p17 and then leave it open and let it run for a while and then try to reopen it to get the old state back, nothing will happen. You need to close the current run of the game and then do a fresh open to get the old version back.

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