Advertisement

Derived class deleting

Started by February 23, 2000 12:37 AM
4 comments, last by Qoy 24 years, 6 months ago
If I have a class that derives from a class, and I delete a pointer to the second class to an object of the first class, then will the whole object be deleted? I know that sounded like mush, so here''s an example:

class A {};
class B : public A {};

void main()
{
 B* foo = new B;
 A* foo2 = foo;
 delete foo2;
}
 
Is my question clear? Basically, I want to know if that code would delete the WHOLE object of foo2, or just the A part of it? ------------------------------ Jonathan Little invader@hushmail.com http://www.crosswinds.net/~uselessknowledge
Good question. AFAIK, the new and delete operators keep track of what is happening with every variable. Deleting the pointer to the object should remove all the data from memory.

If this was not the case, would something like,

whatever* blah = new whatever[20];
delete[] blah;

ever work?
Advertisement
This isn''t going to respond to your code directly.

Depends if your destructor is virtual. Just so you know if you don''t, when dealing with classes like this ( this meaning dynamic allocation/pointers ) then virtual comes into play heavily. Rather than go into details here is the "just" of it:

If the member is NOT virtual -- The operations invoked are a modeled after the "blue print" of the _pointer_type_

If the member IS virtual -- The operations invoked are modeled after the "blue print" of the _type_being_pointed_to_

As far as your post, even though I gave you a hint, I''m going to leave that to you and your debugger. Unwinding your callstack and watching what happens will be more rewarding for you that way. ( Not trying to be an ass )
If you try that and you still don''t understand then post back here and we''ll try again. This kind of post is frequent so hopefully this way will help more than just you. ( Using your debugger and unwinding your callstack to see what is happening that is )

~deadlinegrunt

If the base class has a virtual destructor, the entire object will be deleted (according to dynamic type)

Otherwise, only the destructors of the static type of the pointer and up will be called.

There is almost never any use of having a hierarchy with a base class that has a non virtual destructor.
In short, always make your base classes have virtual destructors. :-)
deadlinegrunt: I guess we wrote it at the same time :-)

just a note. in a class hierarchy, it''s enough to declare the destructor of the base class (root) as virtual.

~deadlinegrunt

This topic is closed to new replies.

Advertisement