user2108296
user2108296

Reputation:

How to delete an object (class) through destructor method

I'm wonder to know is it possible to delete an object through destructor method?

Constructor and destructor of my class:

class cal
{
    public:
        cal()
        {
            days = 0;
            day = 1;
            month = 1;
            year = 1300;
            leap = true;
        };
        ~cal()
        {
            delete this;
        }
}*calendar = new cal;

How can I delete this pointer through class?

P.S

I forgot to write the following code

cal *calandar = new cal[];

I want to use it in heap not stack

I want to use this class (objects) frequently (many of that object) imagine how many time should I write delete and it make hard understanding, troubleshooting and tracing codes I want them to been destroyed automatically (in heap)

I used following code in my class when I exec "delete[] calendar" it reduce my rams occupied (amount of ram that is used) does it work properly (destroy all objects) by exiting program? Because I use GNU/Linus and it destructs all objects with or without that lines I'm concern about leaking in windows

void DisposeObject() { delete this; }

Upvotes: 7

Views: 37889

Answers (3)

Sergey K.
Sergey K.

Reputation: 25386

You can write the code like this:

class cal
{
    public:
        cal()
        {
        };
        ~cal()
        {
        }
        void DisposeObject()
        {
           delete this;
        }
}

And it will call your destructor.

You should not call delete this from your destructor since it will call the destructor recursively, possibly leading to a stack overflow. Anyway, the code you wrote suffers from undefined behavior.

Refer to this question for in-depth discussion: Is delete this allowed?

Upvotes: 11

Mike Seymour
Mike Seymour

Reputation: 254471

No. By the time the destructor is called, the object is already being destroyed, so delete this is not valid.

The behaviour is undefined, but most likely it will call the destructor recursively, leading to a stack overflow.

Upvotes: 15

Reed Copsey
Reed Copsey

Reputation: 564413

I`m wonder to know is it possible to delete an object through destructor method

Even supposing this was valid - The problem is that nothing would ever call the destructor, so this would never have an effect. The destructor is called when the calling code deletes the object, which in turn can delete any internal objects as needed.

In your case, it doesn't look like you need to do anything in your destructor, however, as you don't have any resources being allocated that need to be explicitly deleted (at least in what you're showing).

Upvotes: 3

Related Questions