Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual function call from a normal function

class base
{
public:
    void virtual func(){cout<<"base";}
    void check()
    {
        func();
    }
};
class derived: public base
{
public:
    void func(){cout<<"dervied";}
};
int main()
{
    base *obj = new derived();
    obj->check();
    return 0;
}

Above code prints derived on the console. Now, I understand the concept of virtual functions but I'm unable to apply it here. In my understanding whenever we call a virtual function, compiler modifies the call to "this->vptr->virtualfunc()" and that's how most heavily derived's class function gets invoked. But in this case, since check() is not a virtual function, how does the compiler determine that it needs to invoke func() of derived?

like image 469
Vivek Ranga Avatar asked Jul 02 '26 17:07

Vivek Ranga


1 Answers

how does the compiler determine that it needs to invoke func() of derived?

In the same exat way - by invoking this->vptr->virtualfunc(). Recall that this belongs to the derived class even inside the base class, because each derived class is a base class as well, so the same way of accessing virtual functions works for it too.

like image 113
Sergey Kalinichenko Avatar answered Jul 04 '26 07:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!