Hello. I'm trying to store a child class into it's a pointer of it's baseClass, like this:

baseClass*test = new subClass;

Which works and all, except I'm having trouble using 'delete' to destroy the newly created subClass. So something like this:

baseClass*test = new subClass;
delete baseClass;

Here's a more accurate example of what I'm trying to do, exactly:

#include <iostream>
using namespace std;

class baseClass
{
    public:
        virtual void Blah() = 0;
};

class subClass : public baseClass
{
    public:
        virtual void Blah()
        {
            cout << "I'm sub class 1" << endl;
        }
        ~subClass()
        {
            cout << "Sub class 1 destroyed..." << endl;
        }
};

class subClass2 : public baseClass
{
    public:
        virtual void Blah()
        {
            cout << "Hi there! I'm sub class 2" << endl;
        }
        ~subClass2()
        {
            cout << "Sub class 2 destroyed..." << endl;
        }
};

int main()
{
    baseClass*test;
    int input;
    cout << "Enter 1 or 2:" << endl;
    cin >> input;
    if (input == 1)
    {
        test = new subClass;
    }
    else if (input == 2)
    {
        test = new subClass2;
    }
    else
    {
        cout << "I said, 1 OR 2, bye bye" << endl;
        return 0;
    }
    test->Blah();
    delete test;
    return 0;
}

The "Hi I'm subclass 1/2" thing comes up, but the "Sub class x destroyed..." does not. Leading me to believe that it's not being destroyed. How can I delete the subclass with the 'test' pointer, without knowing if the user entered 1 (for subClass) or 2 (for subClass2)?

Thanks.

Recommended Answers

All 4 Replies

You are indeed correct things are not working correctly:

You problem is simple, you have forgotten to use a virtual destructor in baseClass.

All you have to do is add virtual baseClass() {} to your baseClass
and it will work.

However, please add virtual to your destructors of both your other classes. The general rule is ALWAYS add a virtual destructor if you have virtual functions of any sort. Otherwise you will have problems like this. [Most compilers warn you of this problem if you enable warnings]

@StuXYZ.. just a little important correction, the OP should add:

virtual ~baseClass() {}; //notice the ~ for destructor

check also this thread on a very similar topic.

Awesome, it works now. Thanks for the help guys!

@StuXYZ.. just a little important correction, the OP should add:

virtual ~baseClass() {}; //notice the ~ for destructor

check also this thread on a very similar topic.

One more little correction:

virtual ~baseClass() {} // no semicolon
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.