Reputation: 1029
Suppose I have a class like this
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 gets initialized in the beginning of the constructor. But in this case there is no default constructor, only 2 parameterized constructors. Where will the VPTR be initialized?
Upvotes: 1
Views: 1745
Reputation: 1
Every constructor will first initialize the vptr
pseudo-field. You can imagine that it is the first hidden field of every C++ class having some virtual
member functions.
It is in theory possible to implement virtual functions without a virtual table pointer, but I know no common C++ implementation doing that.
Upvotes: 3
Reputation: 206566
Where is the vptr (virtual pointer) initialized in a class having only parameterized constructors?
To be strictly technical this is completely implementation defined.
However, almost known compilers implement dynamic dispatch through vptr and v-table mechanism. All of these compilers will initialize the vptr to point to its own v-table in each constructor's member initialization list.
Something like:
Base::Base(...arbitrary params...)
: __vptr(&Base::__vtable[0]) ← supplied by the compiler, hidden from the programmer
{
}
This C++ FAQ explains a gist of what exactly happens.
Upvotes: 3