views:

29

answers:

1

Hi All,

I have a template list say,

List<SuperClass*>* mList;

for(int i = 0;i < mList->ElementsCount();i++)
    mList->DeleteElementAtIndex(i);

in mList objects of subclasses are added.

while on deleting object from the list,

should i need to convert the object into corresponding subclasses and call delete method

+3  A: 

No, calling the delete operator on each pointer without explicit conversion is enough, but you must make sure that the destructors of the classes in the class hierarchy are declared as virtual (it's enough to mark just the one of the base class as such). In this way, the call to the destructor will be a virtual call, so the correct destructor will be called.

If you don't declare the destructor as virtual, when calling delete on each pointer the destructor of the base class will be called instead of the correct one; this is the motivation why it's considered almost always an error to have class hierarchies without a virtual destructor.

More info about this can be found in the relevant entry of the C++ FAQ Lite.

By the way, that list doesn't seem to be an STL list (std::list), if so you should remove the STL tag from your question.

Matteo Italia
@Matteo Italia - the info here is relevant for STL containers as well as any custom.
Steve Townsend
Well, it's relevant in general to pointers to base classes. Does any question about pointers be tagged as STL? :)
Matteo Italia