[英]How does a pointer to a Base class which initialized by a derived class can have *__vptr called the right virtual function?
[英]where is the vptr (virtual pointer) initialized in a class having only parameterized constructors?
假設我有一個這樣的班級
class Base
{
private:
int i;
int j;
public:
Base(int i)
{
this->i = i;
j = 0;
}
Base(int i, int j)
{
this->i = i;
this->j = j;
}
virtual void f()
{
cout<<"in base f()"<<endl;
}
};
VPTR在構造函數的開頭初始化。 但是在這種情況下,沒有默認構造函數,只有2個參數化構造函數。 VPTR將在哪里初始化?
每個構造函數都將首先初始化vptr
偽字段。 您可以想象它是每個具有某些virtual
成員函數的C ++類的第一個隱藏字段。
從理論上講,可以在沒有虛擬表指針的情況下實現虛擬功能,但是我不知道普通的C ++實現會這樣做。
在僅具有參數化構造函數的類中,vptr(虛擬指針)在哪里初始化?
嚴格來說,這是完全實現的定義。
但是,幾乎所有已知的編譯器都通過vptr和v-table機制實現動態調度。 所有這些編譯器都將初始化vptr,以指向每個構造函數的成員初始化列表中的自己的v表。
就像是:
Base::Base(...arbitrary params...)
: __vptr(&Base::__vtable[0]) ← supplied by the compiler, hidden from the programmer
{
}
此 C ++常見問題解答說明了實際發生的要點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.