Home Articles Books Downloads FAQs Tips

What's Wrong With This Code? Volume #4


Base class destructors

The code example below contains three classes: Foo, Base, and Derived. The Derived class contains two data members that are Foo objects. One is a pointer, and one is not. Derived publically inherits from Base.

#include <iostream>

using namespace std;

class Foo
{
public:
    Foo()
    {
        cout << "Foo constructor" << endl;
    }
    ~Foo()
    {
        cout << "Foo destructor" << endl;
    }
};

class Base
{
public:
    Base()
    {
        cout << "base constructor" << endl;
    }

    ~Base()
    {
        cout << "base destructor" << endl;
    }
};

class Derived : public Base
{
    Foo  foo1;
    Foo *foo2;
public:
    Derived()
      :Base()
    {
        cout << "derived constructor" << endl;
        foo2 = new Foo;
    }

    ~Derived()
    {
        cout << "derived destructor" << endl;
        delete foo2;
    }
};

//---------------------------------------------------------------------------
int main()
{
    Base *b = new Derived;
    delete b;
    return 0;
}

The output from this program is:

base constructor
Foo constructor
derived constructor
Foo constructor
base destructor

The program seems to run OK. It does not crash and burn, and it does not hang the operating system. On Windows, that's always a major accomplishment. However, the output from the program indicates that something is wrong. Can you find the problem?


Answer


Code for this edition
wwwtc4.zip BCB4 project that contains problem code.
wwwtc4x.zip Same project, includes an EXE (55 kb).


Copyright © 1997-2002 by Harold Howe.
All rights reserved.