Delete a class with multiple inheritance through base pointer?

I

Ian

Given

struct A{...};
struct B{...};

struct C : public A, public B {...}

int main()
{
A* a = new C;

delete a;

return 0;
}

Will the B part of a be correctly deleted?

Ian
 
J

John Harrison

Ian said:
Given

struct A{...};
struct B{...};

struct C : public A, public B {...}

int main()
{
A* a = new C;

delete a;

return 0;
}

Will the B part of a be correctly deleted?

Ian

Its not a question of whether or not the B part will be correctly deleted.
Its a question of whether the code is correct or not, if it is not the
consequences are undefined.

The answer is that the code is correct if A has a virtual destructor,
otherwise you have undefined behaviour.

john
 
G

Gianni Mariani

Ian said:
Given

struct A{...};
struct B{...};

struct C : public A, public B {...}

int main()
{
A* a = new C;

delete a;

return 0;
}

Will the B part of a be correctly deleted?

only if A has a virtual destructor.

i.e.

struct A{ virtual ~A(){} ...}; // not the virtual destructor
struct B{...};

struct C : public A, public B {...}

int main()
{
A* a = new C;

delete a;

return 0;
}
 
I

Ian

I left out the virtual destructors in A and B...

Should work, but I am seeing problems where it does not.
 
J

John Harrison

Ian said:
I left out the virtual destructors in A and B...

Should work, but I am seeing problems where it does not.

What problems are you seeing?

john
 
J

John Harrison

Ian said:
What I think is a compiler bug.... Members of one base being invalid in
the destructor of the derived class.

Ian

Compiler bugs are always a possibility but the code you posted is very
simple (maybe your real code is more complex) so I'd be surprised if a
compiler got that wrong.

john
 
C

Chris Theis

Ian said:
What I think is a compiler bug.... Members of one base being invalid in
the destructor of the derived class.

Could you elaborate on that (probably with some sample code & which compiler
you're using). From your code I do not see a problem (with the virtual
declartions being added) as the order of destruction is simply the reverse
order of construction. Thus the dtor of the derived class is called before
the one of the base class.

Regards
Chris
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top