delete derived class through base class pointer (?)

Z

Zycor

Anybody have good knowledge of delete that can answer this simple
question?

I have a base class that contains pointers to its own type, those
pointers will contain derived classes (acting polymorphic). In the
base class destructor I want to delete the allocated memory. Will this
cause a memory leak?
Code example follows:

A
{
A* a;
~A()
{
delete a;
}
};

B : public A
{
};

A anA;
anA.a = new B;

Zycor
 
R

Rob Williscroft

Zycor wrote in in comp.lang.c++:
Anybody have good knowledge of delete that can answer this simple
question?

I have a base class that contains pointers to its own type, those
pointers will contain derived classes (acting polymorphic). In the
base class destructor I want to delete the allocated memory. Will this
cause a memory leak?

It will cause Undefined Behaviour, IOW Standard C++ says nothing
about what does (or doesen't happen).

To fix the problem give class A a virtual destructor.
Code example follows:

struct

A
{
A* a;
~A()

virtual ~A()
{
delete a;
}
};

B : public A
{
};

A anA;
anA.a = new B;

HTH.

Rob.
 
Z

Zycor

yea the destructor would be virtual, and that would allow any derived
class destructors to be called followed by the base class destructor.
My concern is this; the operator delete takes a void* as an argument,
and optionally a size_t. So for the subsequent free call there must be
knowledge of how much memory was originally allocated. I don't know
how this is tracked. Calling delete on a base class pointer for a
derived class object would free base size_t or derived size_t? And how
does it know?

I imagine it is tracked through the related new call. If so, then it
might be safe. If it somehow considers type, then it may free the
wrong amount of memory, and thus cause a leak...

zycor
 
D

David Harmon

On 16 Dec 2004 15:36:24 -0800 in comp.lang.c++, "Zycor"
yea the destructor would be virtual, and that would allow any derived
class destructors to be called followed by the base class destructor.

That is your answer. You are specifically allowed to delete derived
class instances through a base class pointer, but the base class
must have a virtual destructor.
So for the subsequent free call there must be
knowledge of how much memory was originally allocated. I don't know
how this is tracked.

The library is required to track it. It is not required to reveal
how it does so.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top