Saturday, July 29, 2006

virtual function

Something wrong here:

class A
{
public:
virtual void output()
{printf("it is A\n");}
};

class B:public A{
public:
void output()
{printf("it is B\n");}
};

int main()
{
A a;
a.output();
B b;
b.output();
A *aa;
aa = new B[1];
aa = &b;
(*aa).output();
delete []aa;
return 0;
}


In your code when "aa = &b" is executed, aa is not pointing to the allocated memeory any more. aa now is pointing to an address in the stack. If you delete memeory in the stack, you will get an assertion error.

Here is how to fix it:

int main()
{
A a;
a.output();
B b;
b.output();
A *aa;
A* bb; //need another pointer
aa = new B[1];
bb = &b; //bb is a pointer pointing to memory in the stack (b)
(*bb).output();
delete []aa; //aa is a pointer to the heap
return 0;
}

No comments:

Post a Comment