vptr的解析
class base {
public:
virtual void fn(){}
};
class der : public base {};
我知道编译器在类中提供了一个成员调用 VPTR,该成员在运行时由构造函数使用确切的 VTABLE 进行初始化。我有 2 个问题
1)哪个班级拥有 VPTR。或者所有班级都有单独的 VPTR。
2)当执行语句der d;
时,VPTR在运行时是如何解析的?
class base {
public:
virtual void fn(){}
};
class der : public base {};
I know that compiler provides a member call VPTR in class which is initialised with the exact VTABLE at run time by constructor. I have 2 questions
1) Which class holds the VPTR. or all the class is having seperate VPTR.
2) When executing statement der d;
how VPTR is being resolved at run time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
vtable
是为包含虚函数的类及其派生类创建的。这意味着在您的程序中vtable
将为base
创建class 和 der 类。这些vtables
中的每一个都将包含虚拟函数void fn()
的地址。现在请注意der< /code> 类不包含
void 的定义fn()
,因此它的vtable
包含base
类的void fn()
函数的地址。因此,如果你进行调用就像d.fn();
一样,base
类的void fn()
函数将被执行。vtable
is created for the class that contains virtual function and for the classes derived from it.It means in your programvtable
will be created forbase
class andder
class.Each of thesevtables
would contain the address of virtual functionvoid fn()
.Now note thatder
class doesn't contain the definition ofvoid fn()
,hence itsvtable
contains the address ofbase
class'svoid fn()
function.Thus if u make a call liked.fn();
thevoid fn()
function ofbase
class would get executed.注意:虚拟表和虚拟指针是实现细节,尽管我知道的所有 C++ 编译器都使用它们,但它们不是标准所强制的,只有结果是。
要回答您的具体问题:每个具有虚拟方法(其自己的或继承的)的类的实例或具有(某处)虚拟继承关系的类的实例将至少需要一个虚拟指针。
可以有多个(当涉及虚拟继承或多继承时)。
在您的示例中,单个虚拟指针就足够了。然而,将其视为
类
的一部分是没有意义的。虚拟指针是实例(对象)的一部分,并且存在于类规则之外,因为这些规则适用于语言,并且虚拟指针是一种实现机制。Note: a virtual table and a virtual pointer are implementation details, though all the C++ compilers I know use them, they are not mandated by the Standard, only the results are.
To answer your specific question: each instance of a class with virtual methods (either its own, or inherited ones) or a class with (somewhere) a virtual inheritance relationship will need at least one virtual-pointer.
There can be several (when virtual inheritance or multi-inheritance are involved).
In your example, a single virtual pointer is sufficient. However it does not make sense to speak of it as being part of a
class
. The virtual pointer is part of the instance (object), and lives outsides the classes rules because those apply to the language, and the virtual pointer is an implementation mechanism.如果
类
是多态的(即包含虚拟类
对象都有自己的vptr
> 函数或具有虚拟
继承。)在这种情况下,两个类都具有虚拟
函数。您只是声明
der
的对象。但即使您调用函数,在这种情况下,对任何函数的调用都会在编译时解析。仅当使用指针/引用调用函数时,虚函数解析才会出现。Every
class
object has its ownvptr
if theclass
is polymorphic (i.e. containsvirtual
function or hasvirtual
inheritance.) In this case both the classes hasvirtual
function.You are just declaring the object of
der
. But even if you call a function then in this case the call to any function is resolved at compile time. Virtual function resolution comes into picture only when the function is called with pointer/reference.