John Harrison a écrit :
> iTooo wrote:
>
>> What a subject, mhhh not resumable. Here is my problem:
>>
>> I'm using a template class for lists, upon deletion it deletes its
>> elements, ok, works fine.
>> Trouble comes when I put in this list inherited classes and the list is
>> templated for the parent class. When the list deletes its elements, the
>> destructor called is not the one of the classes, but their parent's.
>>
>> Here is a little example code
>>
>> Class definitions:
>> --
>> class ParentClass
>> {
>> };
>>
>> class NotDeleted : public ParentClass
>> {
>> public:
>> ~NotDeleted() { printf("I was deleted\n"); }
>> };
>>
>> template <class T> class TplClass
>> {
>> public:
>> void DeleteElement(T *elem) { delete elem; }
>> };
>> --
>>
>>
>> Code:
>> --
>>
>> NotDeleted *nd = new NotDeleted();
>> ParentClass *pc = (ParentClass *)nd;
>> delete nd;
>>
>> --> Prints "I was deleted";
>>
>> NotDeleted *nd = new NotDeleted();
>> TplClass<ParentClass> tpl;
>> tpl.DeleteElement(nd);
>>
>> --> Does NOT print anything
>>
>> --
>>
>> The only way I could explain this behaviour is the loss of the instance
>> "real" class when using the template class. Is there a way to work
>> around with it ?
>>
>> Thanks for you help
>
>
> The problem is solved by declaring a virtual destructor in your parent
> class.
>
> class ParentClass
> {
> public:
> virtual ~ParentClass() {}
> };
>
> You should always do this is a base class if there is any possibilty of
> wanting to delete a derived class object through a pointer to the base
> class.
>
> john
Thank you very much, I didn't knew destructors could be virtual as
constructors cannot.
|