Re: call virtual function after the object has been deleted
On 15 Mai, 22:55, ypwang...@gmail.com wrote:
I met a problem and I want to know where is the specification of this:
#include <stdio.h>
class A{
public:
virtual void getName(void) = 0;
};
class B : public A
{ public:
void getName(void){printf("hello,B\n");};
};
int main(void)
{
A* p = new B;
delete p;
p->getName();
}
So what's the behavior of this code?
This code causes undefined behaviour due to two
reasons:
1) You attempt to delete a base class pointer
of an actually derived type, although the base class
has no virtual destructor, see 5.3.5/3:
"In the first alternative (delete object), if the static
type of the operand is different from its dynamic type,
the static type shall be a base class of the operand's
dynamic type and the static type shall have a virtual
destructor or the behavior is undefined.[..]"
2) You attempt to use the pointer of an deleted
object, see 3.7.3/4:
"If the argument given to a deallocation function in
the standard library is a pointer that is not the null
pointer value (4.10), the deallocation function shall
deallocate the storage referenced by the pointer,
rendering invalid all pointers referring to any part of
the deallocated storage. The effect of using an invalid
pointer value (including passing it to a deallocation
function) is undefined."
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]