The following code:
#include <stdio.h>
class Parent
{
public:
virtual void func() {printf("Parent\n");}
};
class Child1 : public Parent
{
virtual void func() {printf("Child1\n");}
};
class Child2 : public Parent
{
virtual void func() {printf("Child2\n");}
};
int main(int argc, char* argv[])
{
Parent & obj = Child1();
obj.func();
obj = Child2();
obj.func();
return 0;
}
yields the following results:
expected: Child1 Child2.
actual: Child1 Child1.
(compiled on VS2010)
I guess that the vptr is not changed by the assignment. It there a way to cause it to be re-created (other than using a pointer to Parent and assigning to it using new)?
thanks
You're calling the default assignment operator on obj, which is still of type Child1, with an argument of type Child2. The object itself is still of type Child1
. You can verify this by implementing operator =
on all 3 classes, and inserting a print statement there.