Search code examples
c++classpolymorphism

vptr - virtual tables


there is something i still don't get.

for every class i declare there is a hidden vptr member pointing to the class virtual table.

let's say i have this declaration :

class BASE
{
    virtual_table* vptr; //that's hidden of course , just stating the obvious
    virtual void foo();
}

class DERIVED : public BASE
{
   virtual_table* vptr; //that's hidden of course also
   virtual void foo();
   virtual void cho();
}

first i want to understand something, is it really the same member name for the vptr both for the derived and the base ?

second, what happens in this situation :

base* basic = new derived();

i get it, the basic variable gets derived's vptr, but how is that happening ? cause usually when conversion taking place , derived's base part (including base's vptr) should be assigned to basic, and not derived's vptr. maybe it's different if there is a variable with the same name in both classes, i dunno.

third and last question : when i have

 base* basic = new derived();

is there a way to call with basic - base's member function even though it's virtual ?

thanks


Solution

  • first, yes, it is the same member. It is automaticaly assigned a first time when running base constructor, and assigned a second time when running the derived constructor. (In the case of default empty constructors, the useless assignements of base is optimized away.)

    second, there is no real conversion. In fact, the derivation can be named a "is a" relationship. In this case, derived "is a" base. If you consider the first bytes of memory of a derived object, they have the same meaning than the first bytes of a base object.

    third, you can call basic member function as follows: basic->base::foo();