Bushido Hacks wrote:
> On Apr 15, 2:01 pm, "simonod" <simonodw...@gmail.com> wrote:
>> On Apr 15, 6:41 pm, "Bushido Hacks" <bushidoha...@gmail.com> wrote:
>>
>>
>>
>>> I think this message got lost the first time I sent it, so I'm
>>> reposting it.
>>> I need a little help with Destructors.
>>> Suppose I created a multidimmensional array in a Base class that was
>>> also accessable in a Derived class, would I need to delete the array
>>> in the Derived class if I declared my destructors as virtual?
>>> class Base
>>> {
>>> public:
>>> ...
>>> virtual ~Base();
>>> protected:
>>> int m; // rows
>>> int n; // cols
>>> double** p;
>>> };
>>> class Derived : public Base
>>> {
>>> public:
>>> ...
>>> virtual ~Derived();
>>> };
>>> Base::~Base()
>>> {
>>> for(int i = 0; i < m; i++){delete[] p[i];};
>>> delete[] p;
>>> };
>>> Derived::~Derived(){
>>> // Should these lines be here?
>>> for(int i = 0; i < m; i++){delete[] p[i];};
>>> delete[] p;
>>> };- Hide quoted text -
>>> - Show quoted text -
>> Hi,
>>
>> For me, the quick answer is you always delete where you new. In your
>> case, if you new'd the array in the base class then you also delete it
>> there (and nowhere else). The fact that the destructor is virtual
>> makes no difference to this fact: what that does is to make sure that
>> delete calls the correct destructor of an object even if you only have
>> a pointer to a base class of that object. Correctly calling a derived
>> class destructor will still mean that the base class destructor gets
>> called too, and you're memory will be free'd.
>>
>> Hope that helps,
>> Si
>
> What if the base class and the derived class both have a assignment
> operator functions? If I use the delete and new functions in the
> derived definition, do I still need those lines in Derived's
> destructor?
>
No, if you delete in the base, it's ok. What sigmonod was trying to tell
you is that if the array is defined in your base class, and is allocated
in your base class, no allocation or deallocation should be done in the
derived class. It's a matter of good programming, not of C++
constraints. You have to try to keep things separated, and to manage
objects in a single class. That is, if not REALLY needed, avoid
protected member variables.
Anyway, your original question actually made sense: the virtual
destructor has a somewhat particular behaviour, because usually when a
virtual method is invoked, only the derived one is actually executed.
Regards,
Zeppe
|