I'm having some difficulty figuring out how to delete the objects I new'ed during run-time. I'm using a heterogeneous collection.

Simplified Example:

const int SIZE = 4;
myBase* objs[SIZE];

objs[0] = new myChild1();
objs[1] = new myChild2();
objs[2] = new myChild3();
objs[3] = new myBase();

//I tried:
for(int i = 0; i < SIZE; ++i)
  delete objs[i];

//but it caused run-time errors (It didn't show any specific errors but would stall the program and not allow it to close.)

How do I properly delete these new'ed objects to prevent memory leaks?
Thanks for any help.

Recommended Answers

All 3 Replies

You haven't shown the definitions of your classes. I presume your MyChild classes are derived from MyBase. In that case, I see nothing wrong with your code except that your MyBase class must have a virtual destructor for it to work correctly.

You haven't shown the definitions of your classes. I presume your MyChild classes are derived from MyBase. In that case, I see nothing wrong with your code except that your MyBase class must have a virtual destructor for it to work correctly.

Yes, myChild classes are derived from myBase. That could be the problem, I didn't make my destructors virtual. I'm going to give that a shot, be back shortly.

That fixed the problem. Thanks. Out of curiosity, why did that cause a problem? I didn't use new in any of my classes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.