So I have a C++ function to which I pass a pointer to a base class, like:
void DoStuffAndAssignPtr(MyBase* ptr)
{
MyBase* p;
//do stuff
if (stuff was awesome) p = new MyAwesome();
else p = new MyBase();
//vftable of p before the return is MyAwesome
(*ptr) = (*p);
}
Now we need to invoke some virtual method that ‘MyAwesome’ and ‘MyBase’ implement differently. However, when checking the return value, as below:
void mainly()
{
MyBase* passMe = new MyBase();
DoStuffAndAssignPtr(passMe);
//now passMe is always being returned with MyBase's vftable
}
We can see that ‘passMe’ is always a ‘MyBase’ (as far as the vftable shows while debugging in VS). Can anyone provide any guidance as to why this is happening, and how I can ensure that ‘passMe’ will invoke ‘MyAwesome’ implementations of virtual methods?
The problem is with the use of
(*ptr)=(*p). You should useptr=p.Only pointer and reference have polymorphism. When you use dereference (the star *), you lose this property, and only the base part is copied from
ptoptr. This is becauseptronly have space for that part of information.