Sign in to follow this  

Polymorphism and dynamic memory allocation problem

Recommended Posts

Koobazaur    1264
Greetings! In my code I have a base abstract class called cBoundedVolume. I derive some children classes from this (for instance, bounded volume defined by planes, a sphere, AABB etc.) Then I have another class called cBoundedVolume_Mixed which allows to create a bounded volume combined of multiple smaller bounded volumes. This class simply contains a vector of pointers to cBoundedVolume; whenever I add a new volume, I simple take a pointer to it, cast it to the base class and add it to my vector. I use virtual functions from the base class to do all of my operations on each such volume, via polymorphysim. However, I arrived at a slight problem. To ensure that my pointers don't magically disappear after the function ends, I allocate the memory dynamically (with new) when my Add Volume function of my mixed class is called. As a safety, I wanted to put delete calls in the destructor of this class. However, if I ever try to pass this class to a function via non pointer/reference, I will create a copy of it, and when the function ends the destructor will be called, which will obliterate my pointers with deletes and the original class will be defunct. The problem is, I don't know how to avoid that (save for manually calling a delete function as opposed to doing it automatically in the destructor). I thought about defining a copy constructor, but the problem is I don't know how to copy my vector of pointers. That is, each pointer is of the Base class, but it actually points to a derived class; thus if I try to copy such object it will only call the Base class copy constructor, which is not enough to copy all the necessary data stored solely in the derived class. Furthermore, I noticed that when I call delete for my pointer, ONLY the base class destructor is called, and not the child's. This, of course, is also bad. How can I ensure I call the child destructor? I thought of defining a virtual Deinit class overloaded in child class, but when I call that in parent's destructor, again, the parent's deinit (not the overloaded child's) is called. Simply put, when I use polymorphysm I lose direct access to my derived classes, which is necessary to copy all of their data when I attemt to copy the object of given class as well as call the destructor of my child class. Is there any way to have the class handle it automatically, without having to explcitly cal virtual Copy() and Delete() functions by my code?

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this