By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,898 Members | 2,012 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,898 IT Pros & Developers. It's quick & easy.

Virtual destructor -- what is correct?

P: n/a
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

Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Paul McKenzie" <pa**@paul.com> wrote in message news:92******************************@news.1usenet .com...
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.
Jul 22 '05 #2

P: n/a
Paul McKenzie wrote:
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.

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.