0

I have 2 classes: DataObject and DataElement. DataObject holds pointers to (only) DataElements, and a DataElement contains pointers to several types, among which a DataObject.

This used to be no problem, since I only use pointers to DataObjects in DataElement, so a forward declaration of DataObject in the header of DataElement is enough.

Now, however, I try to add a destructor to DataElement, in which I need a delete on a DataObject. On this the compiler says:

dataelement/destructor.cc: In destructor ‘DataElement::~DataElement()’:
dataelement/destructor.cc:8: warning: possible problem detected in invocation of delete operator:
dataelement/destructor.cc:8: warning: invalid use of incomplete type ‘struct DataObject’
dataelement/dataelement.h:7: warning: forward declaration of ‘struct DataObject’
dataelement/destructor.cc:8: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.

How can I solve this? A forward declaration is apparently not enough, while I cannot include the complete header for DataObject, since that gives me a circular dependency again.

Thanks in advance!

openbas2
  • 263
  • 1
  • 7
  • 16
  • 2
    Consider using a smart pointer like `shared_ptr`/`weak_ptr`, `scoped_ptr`, or `unique_ptr` (if your implementation supports it); these make resource management in C++ much, much easier and help you to ensure that you code is exception safe and correct. – James McNellis Oct 25 '10 at 16:07

2 Answers2

5

Define the destructor in a .cpp file that includes both headers.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
2

Make the destructor for the first class defined outside of the class body and after the second class, e.g.

class DataElement;

class DataObject
{
    DataElement* elem;
public:
    ~DataObject();
};

class DataElement
{
    DataObject* obj;
public:
    ~DataElement() { delete obj; }
};

DataObject::~DataObject()
{
    delete elem;
}
vitaut
  • 49,672
  • 25
  • 199
  • 336
  • Thanks! I'll go for the solution of James McNellis since it is easier to do right now, but this seems also a good solution. – openbas2 Oct 25 '10 at 16:28