where is the vptr (virtual pointer) initialized in a class having only parameterized constructors?

StackOverflow https://stackoverflow.com/questions/13507554

Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top