Destructor problems.

From: Val (valmont_gaming_at_hotmail.com)
Date: 12/30/03


Date: Tue, 30 Dec 2003 16:32:47 +0100

The code below causes problems when the destructor(s) are called of class
"BaseOne" and "BaseTwo".
Does anyone know how to solve this neatly in ANSI C++? Would be great if
someone knows. It occupies me for some time now.
Here is the code:

//**** Main.cpp **** Our entry point for the app.

#include "BaseOne.h"
#include "BaseTwo.h"
#include "ISomeInterface.h"
#include <iostream>

using namespace std;

int main()
{
 /*This will be deleted correctly by BaseOne and BaseTwo.

 BaseOne(new ISomeInterface);
 BaseTwo(new ISomeInterface);
 */

 /* This will cause a run-time error. Destructors causes it.

 ISomeInterface* IF = new ISomeInterface;
 BaseOne B_1 = IF;
 BaseTwo B_2 = IF;
 delete IF; //<=If one leaves this out then there will be still a run-time
error.
 */

 /* This will cause a run-time error too (Destructor problems).

 ISomeInterface* IF = new ISomeInterface;
 BaseOne B_1;
 BaseTwo B_2;
 B_1.SetIface(IF);
 B_2.SetIface(IF);

 delete IF; //<=If one leaves this out then there will be still a run-time
error.
 */

return EXIT_SUCCESS;
}

//**** ISomeInterface.h ****

#ifndef ISOMEINTERFACE_H
#define ISOMEINTERFACE_H

class ISomeInterface
{
public:
 ISomeInterface() {}

private:

};

#endif // ISOMEINTERFACE_H

//**** BaseOne.h ****

#include "ISomeInterface.h"

class BaseOne
{
public:
 void SetIface(ISomeInterface* iface) { delete IFace; IFace = iface; }

public:
 BaseOne(ISomeInterface* iface) : IFace(iface){}
 BaseOne () : IFace(0) {}
 ~BaseOne() { delete IFace; }

private:

 ISomeInterface* IFace;
};

//**** BaseTwo.h ****

#include "ISomeInterface.h"

class BaseTwo
{
public:
 void SetIface(ISomeInterface* iface) { delete IFace; IFace = iface; }

public:
 BaseTwo(ISomeInterface* iface) : IFace(iface){}
 BaseTwo() : IFace(0) {}
 ~BaseTwo() { delete IFace; }

private:

 ISomeInterface *IFace;
};