Advertisement Jump to content
Sign in to follow this  
luasitdown

Why does a abstract class need destructor?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
You may want to delete an object using a pointer to its base class. Therefore, the base class needs a virtual destructor. Abstract classes can have data, too.

Share this post


Link to post
Share on other sites

class emptyBase {
virtual emptyBase() {} // make sure there is a dtor
} // oops, no virtual dtor

class derived : public emptyBase {
std::string thingThatRequiresCleanup;
}

int main() {
emptyBase* polymorphicPtr = new derived();
// ... do stuff
delete polymorphicPtr;
// the default, non-virtual emptyBase::~emptyBase() gets called on the object
// and therefore thingThatRequiresCleanup doesn't get cleaned up.
// the std::string leaks memory, or worse.
}

Share this post


Link to post
Share on other sites
every constructor needs destructor. Destructors are way of saying to operating system that constructor is no longer using the this memory and thus giving it to the O.S.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!