2-Lee
2-Lee

Reputation: 353

c++ delete pointer of a derived class which is assigned to a pointer of the base class

I have following code:

/* Example OOPBEI03.CPP  */
#include <iostream>

using namespace std;

typedef char item;

class stack
{
private:
    int p;
protected:
    item *st;
public:
    stack(int m=100)
    {
        st = new item[m];
        p = 0;
    }

    ~stack()
    {
        delete [] st;
    }

    void push(item v)
    {
        st[p++] = v;
    }

    item pop()
    {
        return st[--p];
    }

    int empty()
    {
        return !p;
    }
};

class queue : public stack
{
private:
    int q;
    item *qp;
public:
    queue(int m=50):stack(m)
    {
        q = 0;
        qp = st;
    }

    ~queue()
    {
        delete qp;
    }

    item deque()
    {
        return qp[q++];
    }
};

int main()
{
    stack s(50);
    queue q(20);

    s.push('a');
    q.push('b');
    s.push('c');
    q.push('d');

    cout<<"pop   "<<s.pop()<<endl;
    cout<<"pop   "<<s.pop()<<endl;
    cout<<"deque "<<q.deque()<<endl;
    cout<<"deque "<<q.deque()<<endl;
    cout<<"empty queue? "<<q.empty()<<endl;
    cout<<"empty stack? "<<s.empty()<<endl;

    getchar();
    return 0;
}

I get at the end of main() in Visual Studio following error: "Debug Assertion Failed! ... _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)".

If I uncomment the delete operation either in the destructor of the class queue or stack (I uncomment only one operation!), I have no problems.

How can I solve this?

Upvotes: 0

Views: 178

Answers (2)

borisbn
borisbn

Reputation: 5054

Deleting qp should me the same as newing (it's term of mine))).

delete [] qp;
       ^^

But in this particular case deleting qp should be removed at all

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145429

you're deleting the pointer both in the stack base class and in the queue derived class.

let your stack class handle the ownership, don't delete it also in queue

by the way you should make copy construction and copy assignment private, or else handle it (known as the "rule of three"); otherwise these classes can easily be used in ungood ways...


in code that isn't just for learning, just use std::stack and std::queue instead of implementing such classes yourself

std::stack and std::queue are class templates with customizable underlying container type

Upvotes: 1

Related Questions