Nathan822
Nathan822

Reputation: 198

Implementation of destructor as a function?

I have a question about a destructor's implementation for a class. I understand the right way is using the ~ operator, but take a look at the following code:

class foo
{
private:
int* abc;

public:
foo()
{
abc = new int(2);
}

~foo()
{
delete abc;
}

void func()
{
delete abc;
}
}

Now let us say that the main function is defined as below:

int main(int argc, char** argv)
{
foo a;
a.func();
}

Upon the function call of func() in main, does this work in the exact same way as the destructor? What is the difference between the destructor and this function in any similar setting?

Upvotes: 0

Views: 3907

Answers (2)

Cornstalks
Cornstalks

Reputation: 38238

func() and ~foo() do the exact same thing. And that's the problem. When a goes out of scope, its destructor ~foo() will automatically be called, resulting in abc being deleted twice. One way to get around it would be to set abc to NULL at the end of func() after the delete, so that when the destructor gets called it deletes a NULL pointer, which is a special case in C++ where nothing is actually done and is a valid operation.

Or, of course, the code could be rewritten in a way that actually made sense and accomplished something.

And just to be really clear, the "difference" between func() and ~foo() is how/when they're called, not in what they do. func() is manually called by the user, while ~foo() is automatically called when the variable goes out of scope. func() may be called zero or more times (it's up to the programmer), but the compiler will call ~foo() exactly once (no more, no less) in this code.

Upvotes: 5

Karthik T
Karthik T

Reputation: 31972

Few differences beyond the obvious differences in definition.

Destructor

  • invoked automatically at the end of scope or at a delete call, can be invoked manually, rarely a good idea

  • Calls destructors of member variables and base classes.

Run of the mill Method

  • invoked manually

In this particular case, no base classes and only member field is the int * ptr which doesnt have a destructor, so in this case they are identical except for the method of invocation.

Upvotes: 1

Related Questions