Virtual Functions Object Slicing

青春壹個敷衍的年華 提交于 2019-11-28 04:12:36

问题


My question is with reference to this question which explains how virtual functions work in case of object slicing which end up calling base class virtual function and Wikipedia article which explains the virtual table layout for a derived class for below code

    class A{

    public:
     virtual void func(){ cout<<"\n In A:func";}
    };

    class B:public A{

    public:
     virtual void func(){ cout<<"\n In B:func";}
    };

   main(){
    A *ptr1 = new B();

    A oA = *ptr1;

    oA.func(); 
  }




      DerviedClassObjectB:
         +0: pointer to virtual method table of B 

       virtual method table of B:
         +0: B::func

Above program outputs "In A::func" .

But how does without virtual table for class B knowing about base class A::func ends up calling A::func


回答1:


"Virtual table for class B"? Virtual table for class B is not involved in oA.func() call at all. Object oA has type A, which means that its virtual table is that of class A.

Moreover, most compilers will optimize the oA.func() call so that it won't use any virtual tables at all. Since the type of oA is known at compile time, the oA.func() call can be immediately directed to A::func without using any virtual tables.




回答2:


A oA = *ptr1;

This copies any member variables into a new A object. The vtable pointer is not a normal member variable and is not copied. Thus any subsequent virtual functions called against this object will act as if it is an A object, because it is an A object.



来源:https://stackoverflow.com/questions/3479712/virtual-functions-object-slicing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!