虚函数对象切片
我的问题是参考这个问题,它解释了虚拟函数在情况下如何工作对象切片最终调用基类虚函数和维基百科文章解释了虚拟表布局对于以下代码的派生类
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
上面的程序输出“In A::func”。
但是,如果类 B 的虚表不知道基类 A::func,那么如何最终调用 A::func
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这会将所有成员变量复制到新的 A 对象中。 vtable 指针不是普通的成员变量,并且不会被复制。因此,针对该对象调用的任何后续虚拟函数都将表现为它是一个 A 对象,因为它是一个 A 对象。
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.
“
B
类的虚拟表”?B
类的虚拟表根本不参与oA.func()
调用。对象oA
具有类型A
,这意味着它的虚拟表是类A
的虚拟表。此外,大多数编译器都会优化 oA.func() 调用,以便它根本不会使用任何虚拟表。由于
oA
的类型在编译时已知,因此oA.func()
调用可以立即定向到A::func
,而无需使用任何虚拟表。"Virtual table for class
B
"? Virtual table for classB
is not involved inoA.func()
call at all. ObjectoA
has typeA
, which means that its virtual table is that of classA
.Moreover, most compilers will optimize the
oA.func()
call so that it won't use any virtual tables at all. Since the type ofoA
is known at compile time, theoA.func()
call can be immediately directed toA::func
without using any virtual tables.