Search code examples
c++classinstantiationinstances

Why does delete only work in main and not in a function that gets as an input the object or objects to be deleted?


I am trying to create two classes whose instances get created and deleted together. One class is a base for the other:

class Interface;

class MyClass
{
friend class Interface;
private:
  MyClass() {}
public:
  static MyClass *NewInstance();
  Interface *ControlPanel;
};

class Interface : public MyClass
{
friend class MyClass;
private:
  Interface() {}
public:
  void Control1() {cout << "control1" << endl;}
  void Control2() {cout << "control2" << endl;}
  void Control3() {cout << "control3" << endl;}
};

The two member functions that are supposed to create and delete instances are:

MyClass *MyClass::NewInstance()
{
  MyClass *inst = new MyClass;
  inst->ControlPanel = new Interface;
  return inst;
}

void DeleteMyClassInstance(MyClass *inst)
{
  delete inst->ControlPanel;
  inst->ControlPanel = 0;
  delete inst;
  inst = 0;
}

I had success in linking the instance creation process with the use of a function in the base class (NewInstance()) which creates the instances. But the deletion function (DeleteMyClassInstance()) doesn't work (that is, I can still use both inst1 and inst1->ControlPanel after calling the function):

int main()
{
  MyClass *inst1 = MyClass::NewInstance();

  inst1->ControlPanel->Control1();

  DeleteMyClassInstance(inst1);

  inst1->ControlPanel->Control1();

  return 0;
}

But if I put the deletion code inside the main function, it works perfectly (the inst1->ControlPanel->Control1() statement that comes after the delete statements doesn't work, and that's what I want):

int main()
{
  MyClass *inst1 = MyClass::NewInstance();

  inst1->ControlPanel->Control1();

  delete inst->ControlPanel;
  inst->ControlPanel = 0;
  delete inst;
  inst = 0;

  inst1->ControlPanel->Control1();

  return 0;
}

My question is: Why does putting the delete statements directly inside the main function work while putting them inside a separate function and using it in main doesn't? Why does the code in my DeleteMyClassInstance() function get ignored by the compiler?


Solution

  • Change your DeleteMyClassInstance function to.

    void DeleteMyClassInstance(MyClass **inst)
    {
      delete (*inst)->ControlPanel;
      (*inst)->ControlPanel = 0;
      delete (*inst);
      *inst = 0;
    }