Virtual destructor -- what is correct?

P

Paul McKenzie

Consider the following:

class A
{
public:
A() { }
~A() { }
};

class B : public A
{
public:
B() { }
virtual ~B() { }
};

class C : public B
{
public:
C() { }
};

int main()
{
B *pB = new C;
delete pB;
}

I am having a debate of whether the "delete pB" invokes undefined behavior.
I believe it does invoke undefined behavior.

However someone else has claimed that since the base pointer defined in
main() is to a B, and B has a virtual destructor, deleting
through a pointer to B, is safe (no undefined behavior).

My claim is that regardless of whether B has a virtual destructor, the base
class A, has a non-virtual destructor,
therefore the code invokes undefined behavior.

Who is correct in this regard?

Paul
 
R

Ron Natalie

Paul McKenzie said:
However someone else has claimed that since the base pointer defined in
main() is to a B, and B has a virtual destructor, deleting
through a pointer to B, is safe (no undefined behavior).

This is the correct answer. It is the static type passed to delete that
must have the virutal destructor.
 
R

Rolf Magnus

Paul said:
Consider the following:

class A
{
public:
A() { }
~A() { }
};

class B : public A
{
public:
B() { }
virtual ~B() { }
};

class C : public B
{
public:
C() { }
};

int main()
{
B *pB = new C;
delete pB;
}

I am having a debate of whether the "delete pB" invokes undefined
behavior. I believe it does invoke undefined behavior.

However someone else has claimed that since the base pointer defined
in main() is to a B, and B has a virtual destructor, deleting
through a pointer to B, is safe (no undefined behavior).

My claim is that regardless of whether B has a virtual destructor, the
base class A, has a non-virtual destructor, therefore the code invokes
undefined behavior.

Who is correct in this regard?

I'm afraid "someone else" is correct. If you want to delete a C through
a pointer to B, the system must dispatch the destructor call to the
right class (i.e. C instead of B), and for that, a virtual destructor
in B is sufficient.
 

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,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top