Search code examples
c++polymorphismvirtual-functionsvptr

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


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?


Solution

  • 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.