[comp.lang.c++] deleting objects with virtual bases

stan@hcr.UUCP (Stan Jarzabek) (09/07/89)

Is it legal to delete an object with a virtual base through base pointer?

class A
{ int a; };

class B : virtual public A
{ int b; };

class C : public B
{ int c; };

main()
{
	A* ap = new C;  
	delete ap;

	C* cp = new C;  //core dumped
}

As 'ap' does not really point to the beginning of the area allocated by 'new C',
'delete ap' causes a problem. (In 2.0, operator delete() calls free().)
In fact, a subsequent call to operator new() causes core dump. The same problem 
may occur when you delete an object with multiple bases through a base pointer.

The language manual does not address this issue: is this a language definition 
problem, the problem of current implementation, or the thing a user should be 
responsible for?

Stan Jarzabek

ark@alice.UUCP (Andrew Koenig) (09/12/89)

In article <1984@hcr.UUCP>, stan@hcr.UUCP (Stan Jarzabek) writes:

> Is it legal to delete an object with a virtual base through base pointer?

Sure, as long as the base class has a virtual destructor.
That's true whether the base class is virtual or not --
if class D is derived from B and you use a B* to delete a
D object, then B must have a virtual destructor.
-- 
				--Andrew Koenig
				  ark@europa.att.com

dog@cbnewsl.ATT.COM (edward.n.schiebel) (09/12/89)

From article <1984@hcr.UUCP>, by stan@hcr.UUCP (Stan Jarzabek):
> 
> Is it legal to delete an object with a virtual base through base pointer?
Yes, but the destructor better be virtual.

	Ed Schiebel
	AT&T Bell Laboratories
	dog@vilyia.att.com

shopiro@alice.UUCP (Jonathan Shopiro) (09/14/89)

In article <1984@hcr.UUCP>, stan@hcr.UUCP (Stan Jarzabek) writes:
- 
- Is it legal to delete an object with a virtual base through base pointer?
- 
- class A  { int a; };
Use

	class A
	{
		int a;
	public:
			virtual ~A() {}
	};

- 
- class B : virtual public A  { int b; };
- 
- class C : public B  { int c; };
- 
- main()
- {
- 	A* ap = new C;  
- 	delete ap;
- 
- 	C* cp = new C;  //core dumped
- }
- 
- As 'ap' does not really point to the beginning of the area allocated by 'new C',
- 'delete ap' causes a problem. (In 2.0, operator delete() calls free().)
- In fact, a subsequent call to operator new() causes core dump. The same problem 
- may occur when you delete an object with multiple bases through a base pointer.
- 
- The language manual does not address this issue: is this a language definition 
- problem, the problem of current implementation, or the thing a user should be 
- responsible for?
- 
- Stan Jarzabek

All this will work fine if the base class has a virtual destructor.
It can be empty.  The virtual function mechanism takes care of fixing
up the ``this'' pointer so the called function ses the object it
expects.

As a general rule, any class that has any virtual functions should
have a virtual destructor.

-- 
		Jonathan Shopiro
		AT&T Bell Laboratories, Warren, NJ  07060-0908
		research!shopiro   (201) 580-4229