Understand Virtual functions Internals

I am just trying to understand the virtual fns. concept.

I know that if I have a virtual fn. in a base class and its overridden fn. in derived class then based upon the address of base/derived object stored in the base class pointer the fns. will be called.

In the below code I had kept the show() fn. as virtual and it used to call properly the base and derived classes show().

But when I removed the virtual tag from show() then why does not it calls derived show() inspite of base class pointer having address of derived class object?

 
class base
{
public:
    base()
    {
        printf("Base Cons\n");
    }
 
    void show()
    {
        printf("Base Show\n");
    }
};
 
class der: public base
{
public:
    der()
    {
        printf("Der Cons\n");
    }
 
    void show()
    {
        printf("Der Show\n");
    }
};
 
void yahoo(base* bpointer)
{
    printf("Address in base pointer = %u\n",bpointer);
    bpointer->show();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    class base bobj, *bptr;
    class der dobj;
 
    bptr = & bobj;
    printf("Base obj adress = %u\n",&bobj);
    yahoo(bptr);
 
    bptr = &dobj;
    printf("Base obj adress = %u\n",&dobj);
    yahoo(bptr);
 
    return 0;
}

Output of code:

Base Cons
Base Cons
Der Cons
Base obj adress = 1245027
Address in base pointer = 1245027
Base Show
Base obj adress = 1245003
Address in base pointer = 1245003
Base Show

If you remove the virtual keyword then the function doesn't get put into the virtual function table. Therefore, I believe any calls to the function are bound to the function within the type's class. Since yahoo is using base, all calls it makes inside that class are bound to base's function. However, virtual functions are always bound to the vtable (unless you explicitly override it).

1 Like

In effect, 'virtual' is what allows the program to tell whether your object is one class or another at runtime. If the base class member isn't virtual, using a 'base *' pointer will never call anything but members inside of 'base'.