• Popular Now

• 10
• 12
• 12
• 14
• 16

Archived

This topic is now archived and is closed to further replies.

Virtual Destructor??

This topic is 6071 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I have a class called actor which many other classes derive from. The actor class has lots of member variables. Should I use a virtual destructor to free that memory and if I should, how do it do it ? Johan Torp - http://www.destruction.nu

Share on other sites
you should define a destructor that virtual but not abstract.

  class Actor{... virtual ~Actor();...private: char* szName;...}Actor::~Actor(){ delete[] szName;}

Share on other sites
a simple rule from my c++ gourou

"Define a virtual destructor unless you never want anyone to derive from your class"

Share on other sites
What is a pure destructor for? This came up once before, but no one knew...

Magmai Kai Holmlor
- Not For Rent

Share on other sites
A class with only a pure destructor and no other members means the class itself cannot be instantiated, all derived class destructors are virtual, and a derived class must provide a destructor. I don''t think there''s anything more to read into it.

Share on other sites
same thing can be done with protected constructor, so no real reason for it

Share on other sites
To add a little to what spillsome said, all classes that are derived from should have the destructor declared virtual. It''s usually safer to declare it virtual if you are not sure. Only have a non-virtual constructor if you know exactly why. I believe Scott Meyers has as one of his rules that you shouldn''t inherit from concrete classes - although now I''m trying to recall if a derived class will automatically have a virtual destructor if the base class does. Maybe this is one of those implementation-dependent things.

Speaking of which, it''s the implementation-dependent aspect of this issue that is why you should explicitly declare the destructor virtual. This was discussed in C/C++ Users'' Journal, February 2001 in an article by Andrew Koenig. I believe it was taken from his book Accelerated C++. It also came up again in Sutter''s Mill in the September 2001 issue, and I assume it would be in his books as well (Exceptional C++ and/or More Exceptional C++).

I reccomend CUJ to anyone who programs in C or C++. It''s full of wholesome goodness Well, at least, there''s an awful lot that can be learned from reading it, even the articles you think won''t interest you.

--

Games, Anime and more at GKWorld

Meet Bunny luv'' and the girls, ready to perform on your desktop just for you (warning: adult content).