Jump to content
  • Advertisement
Sign in to follow this  

Inheritance and Memory Management

This topic is 2859 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


I'm working in C++ . I have an abstract class and some derived classes.

If I delete an instance of any base class, all the memory handling is correct. However, if, when using polymorphism, I delete an instance of a base class, as the abstract class, then only the abstract class' destructor is called.

As an example, suppose I have an abstract class "Texture", and base classes "Texture1D", "Texture2D", and "Texture3D" (similar to actuality). By way of pseudocode:[source lang="cpp"]class Texture { /*blah*/ }
class Texture1D : public Texture { /*blah*/ }
class Texture2D : public Texture { /*blah*/ }
class Texture3D : public Texture { /*blah*/ }

void some_function(void) {
//All good.
Texture2D* a = new Texture2D();
delete a;

//Problem. Texture2D::~Texture2D() is NEVER called, so memory leak.
Texture* b = new Texture2D();
delete b;
My initial attempt was to make a pure virtual method in the abstract class, and have the abstract class' destructor invoke it. The method would perform cleanup. However, this causes a compile error because base classes' destructors are called before their superclass'.

So . . . I understand the problem. Don't know how to fix it in a clean way.


Share this post

Link to post
Share on other sites
Put a virtual destructor in the base class. Then "delete baseptr;" will ensure the correct destructor(s) are called.

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!