Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Delete

class Shape
{
public:
Shape() { }
virtual ~Shape() { }
virtual void draw() = 0;
};

class Circle : public Shape
{
public:
Circle() { }
virtual ~Circle() { delete this; }
void draw() { cout << "Drawing Circle\n"; }
};

main()
{
Circle x;
Circle *ptr= &x;
ptr->draw();
delete ptr;
}

Can someone please tell me whether the delete in the destructor is correct ? The code works, but when I'm debugging I'm getting Unhandled Exception messages.
[585 byte] By [ami] at [2007-11-11 10:00:09]
# 1 Re: Delete
You are trying to delete the object twice(in fact thrice), so you got the exception, objects destroyed automatically in the destructor, so no need to call "delete this" , "delete ptr" .
venkat78 at 2007-11-11 20:59:32 >
# 2 Re: Delete
Never call delete this in a destructor! The destructor doesn't know whether *this is an automatic object, a static object or one that was allocated using new.
Secondly, you should never call delete with a pointer to a local automatic object, as is ptr. The object to which ptr is pointing, x, is automatically destroyed.
Danny at 2007-11-11 21:00:43 >