Virtual Functions Object Slicing

后端 未结 2 1608
-上瘾入骨i
-上瘾入骨i 2020-12-19 11:53

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 Wikip

相关标签:
2条回答
  • 2020-12-19 12:07
    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.

    0 讨论(0)
  • 2020-12-19 12:24

    "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.

    0 讨论(0)
提交回复
热议问题