Search code examples
c++classderivedvirtual-destructor

Call Destructor of derived ClassObjects via BaseClass List


i got this class to get a list of all derived objects

Register.h
-----------------
class Register {
...
public:

// static object list
static list<Register*> instances;

// default constructor for register object
Register::Register();

// virtual destructor to clean up with subobject destructor first
virtual Register::~Register();

// default methods for this class
static void Register::stop();

Register.cpp
-----------------
#include "Register.h"

// list with all object instances made by this programm
list<Register*> Register::instances;

// default destructor
Register::~Register() {
  list<Register*>::iterator p = find(instances.begin(), instances.end(), this);
  if (p != instances.end()) {
    instances.erase(p);
  }
}

// erase all instances clean up the dish
void Register::stop() {
  // last log message
  Log::write("register cleanup");
  // stops the logging object
  Log::stop();
  // clean up instances
  list<Register*>::iterator iter = instances.begin();
  list<Register*>::iterator end  = instances.end();
  while (iter != end) {
    cout<< endl << (*iter) -> typeName << endl;
    //delete *iter;
  }
  Register::instances.clear();
}

and derived classes

File.h
-----------------
class File : public Register {
...
// default destructor
virtual File::~File(void);
...
}

File.cpp
-----------------
// default destructor
File::~File(void) {
  cout << "file destr";
  this -> deleteFile();
}

Log.h
-----------------
// this class implements a log handler
// (derived from register)
class Log : public File {

public:
  // singelton logging object
  static Log* log;

  // default destructor
  Log::~Log(void);

Log.cpp
-----------------
using namespace std;

// declare pointer for easy logging
Log* Log::log = NULL;

// default destructor
Log::~Log(void) {
cout << "log destr";
}

now i want to delete the whole structure with simply delete the list and the objects in it..

i tried with

 Main.cpp
-----------------
 int main (int argc, char *argv[], char *envp[]) {

   Register::stop();

   return 1;
 }

but the objects are still instanced

i´m out of ideas ^^

kindly..


Solution

  • Register::instances.clear();

    This clears list of pointers, but doesn't do anything with objects. You need to remove them yourself before clearing the list, e.g. like this

    for (list<Register *>::iterator it = Register::instances.begin();
         it != Register::instances.end();
         ++it) {
        delete *it;
    }
    Register::instances.clear();