Why C++ virtual function defined in header may not be compiled and linked in vtable?

后端 未结 5 1320
既然无缘
既然无缘 2021-01-05 14:33

Situation is following. I have shared library, which contains class definition -

QueueClass : IClassInterface
{
   virtual void LOL() { do some magic}
}
         


        
5条回答
  •  长发绾君心
    2021-01-05 14:46

    If this example is simplified, and your actual inheritance tree uses multiple inheritance, this might be easily explained. When you do a typecast on an object pointer, the compiler needs to adjust the pointer so that the proper vtable is referenced. Because you're returning a void *, the compiler doesn't have the necessary information to do the adjustment.

    Edit: There is no standard for C++ object layout, but for one example of how multiple inheritance might work see this article from Bjarne Stroustrup himself: http://www-plan.cs.colorado.edu/diwan/class-papers/mi.pdf

    If this is indeed your problem, you might be able to fix it with one simple change:

    IClassInterface *globalMember = new QueueClass();
    

    The C++ compiler will do the necessary pointer modifications when it makes the assignment, so that the C function can return the correct pointer.

提交回复
热议问题