-
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.
-
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" .
-
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 Kalev
Similar Threads
-
By funwithdolphin in forum C++
Replies: 2
Last Post: 11-15-2005, 11:24 AM
-
By vbcoder in forum VB Classic
Replies: 9
Last Post: 04-28-2005, 12:36 PM
-
By Arthur Wood in forum VB Classic
Replies: 3
Last Post: 04-01-2002, 03:14 PM
-
By Michael Culley in forum VB Classic
Replies: 6
Last Post: 02-12-2002, 03:30 AM
-
By Ted McNeal in forum Database
Replies: 5
Last Post: 12-07-2000, 01:58 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks