1

How to correctly delete base class elements

base class:

class node
{
private:
    node *left, *right, *parent;
public:
    node(node* parent,node* left,node* right);
};

subclass:

class nodeFunc: public node
{
private:
    int x;
public:
    nodeFunc(int x, node* parent, node* left, node* right);
};

class, which contains vector:

class tree
{
private:
    vector<node*> nodes;
public:
    tree(int size);
    ~tree();
};

in constructor:

tree::tree(int size)
{
    for (int i = 0; i < size; i++)
        nodes.push_back( new nodeFunc(i,NULL,NULL,NULL) );
}

destructor:

tree::~tree()
{
    for (vector<node*>::iterator it=nodes.begin();it!=nodes.end();++it)
    {
        delete (*it);
    }
    nodes.clear();
}

in main.cpp:

int main()
{
    tree* myTree = new tree(10);
    delete myTree;
    cout<<"end"<<endl;
}

I use debugger to see what happened in every line. After first, myTree->nodes contains 10 elements. After delete myTree->nodes contains 58 items.

  • 1
    Too many news. The news in main are not necessary. Look into `std::unique_ptr` and `std::shared_ptr` and see if they are suitable for your code. – Neil Kirk Aug 13 '15 at 19:03

1 Answers1

1

After the line delete myTree;, the pointer myTree becomes invalid, because it points to deallocated memory. You cannot dereference it.

As for deleting base class objects, you just need to implement a virtual desctructor in the base class: virtual ~node( );.

Kirill
  • 162
  • 8
  • what's definition of this destructor? –  Aug 13 '15 at 19:10
  • It depends on what you want to do during the deletion of the object. If you just need a polymorphic base class, then you leave implementation empty: virtual `~node( ) { }` – Kirill Aug 13 '15 at 19:15
  • I think you have to read about virtual destructors and their meaning. For example, here: http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – Kirill Aug 13 '15 at 19:18
  • ok but why after 'delete myTree', 'myTree->nodes' dont have 0 items. In tree destructor I have 'nodes.clear()' –  Aug 13 '15 at 20:06
  • Yes, that's normal. I said in my answer, that after you delete `myTree` object, it becomes invalid because it points to deallocated memory. I advice you to learn about C/C++ pointers and memory allocation, for example, here: http://stackoverflow.com/questions/15604411/memory-allocation-deallocation – Kirill Aug 14 '15 at 07:54