What happens when the base class object calls the derived class function (which is non-virtual)

advertisements

Pardon me if the question found silly to you. I am a newbie to c++ and I was studying rum time polymorphism. I want to know what happens when base class object calls derived class function (which is non virtual). for example look at the code

class base {
    public:
        virtual void vfunc() {cout << "This is base's vfunc().\n";}
};

class derived1 : public base {
    public:
        void vfunc() {cout << "This is derived1's vfunc().\n";}
};

int main()
{
    base *p, b;
    derived1 d1;

    p = &b;
    p->vfunc();

    p = &d1;
    p->vfunc();

    return 0;
}

I got the desired ouput, I then removed the virtual keyword from the base class and when I ran the program the output is

This is base's vfunc().
This is base's vfunc().

I will be very thankful if some one explain what happened (in terms of pointer manipulation) in both of the cases

Thanks


In the virtual case, at runtime, p->vfunc() tells p to go to the class definition of the class (whatever part of it is in memory) that the pointee belongs to, and read its vtable (or some similar alternate implementation) to figure out which function to call.

Suppose the vtables look like below:

base's vtable:

----------------
vfunc | 0x2048
----------------

derived1's vtable:

----------------
vfunc | 0x2096
----------------

Then base version or derived version of vfunc is called depending on where vtables point.

In non-virtual case, none of this happens, and the function to call is set in stone by the compiler at compile time. During compile time, all the compiler can figure out is that p is of type 'pointer to base' and changes all the p->vfunc() calls to point to address 0x2048.