"V Patel" <vz******@veriz on.netwrote in
news:kY******** *****@newsfe09. lga:
I am trying to understand the behaviour for the following two cases:
class A {
virtual funcA() {i++;}; // case 1
funct A() {i++;}; // case 2
private:
int i;
};
main ()
{
A *a = new A();
A *b = a;
delete a;
b->functA()
Undefined Behaviour. Dereferencing a pointer to deleted memory. Anything
could happen.
}
case 1 fails (is this because it has to go thru vptr table and the
object is gone)
case 2 ok. (is this because its static binding. Though no object.
Isn't this unsafe?)
Also, a couple of nitpicks:
1) funcA() has no return type. Invalid.
2) case 2: What type is "funct" ? And this function has no return
statement... Undefined Behaviour (falling off the end of a function that
has a return type w/o a return statement).
3) case 2: this looks like a constructor, but has a return value, also not
allowed.
4) main doesn't have a return type. Also invalid. You must declare it
with an 'int' return type (to be Standard compilant).
Also, are default constructor, copy constructor etc required from mere
presence
of any virtual function (non-trivial case) in a class?
Nope. However, a virtual destructor is highly recommended as deletion of a
subclass via a base class pointer, and the destructor _isn't_ virtual leads
to Undefined Behaviour too.