1
votes

I'm trying to add derived objects into an array of base pointers.

My class definition has the following(As this is an assignment it can not be changed):

Base** bases;

Right now I'm using an array of base pointers:

Base** bases=new Base*[2];

And adding elements like so:

bases[0]=new Derived1;
bases[1]=new Derived2;

This works fine if not for the memory leaks that I can't seem to trace. I read I can use vectors for similar purposes with better memory management.

I tried:

vector<Base*>basesV;
basesV.push_back(new Derived1);
basesV.push_back(new Derived2);

It seems to work but how do I 'attach' the vector basesV into my class Base** bases?

Simply bases=basesV; doesn't seem to work. Am I stuck using an array of base pointers?

I also have a function that takes in Base** and dropping the above vector doesn't seem to work as well.

Thanks for any help.

1
If this is an assignment, it seems unlikely that working around the entire thing by hooking in a vector is going to be acceptable. It's a "clever sod" workaround for the constraints of the assignment. It would be better if we could see how you're freeing resources so that we can help you with the memory leak, but you didn't submit a testcase. - Lightness Races in Orbit
Though I do applaud you for recognising that, in the real world, a vector would make far more sense. In that real world, though, try not to store raw pointers. - Lightness Races in Orbit
Ya I'm emailing the prof about this. The actual mandate is, you have to use the supplied header files. All we were given is a paragraph on what the program supposed to do, the header files, and a print out of the program in action. vectors still gives me leaks, it isn't as automated as I thought...(see my reply to the answer below). - cppStud
Well, you're storing pointers. Those pointers are cleaned up. But you still need to clean up the pointees. Typically, as I said, you do not want to store raw pointers. - Lightness Races in Orbit
You still haven't shown us where you delete all these objects....? - Lightness Races in Orbit

1 Answers

0
votes

If I understand correctly...

bases = &basesV[0];

Also make sure your Base destructor is virtual.