user3191398
user3191398

Reputation:

How to correctly delete base class element

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.

Upvotes: 1

Views: 124

Answers (1)

Kirill
Kirill

Reputation: 182

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( );.

Upvotes: 1

Related Questions