Reputation: 75
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?
Upvotes: 2
Views: 251
Reputation: 182753
Exactly the way you said, by using the vptr
in the class member. It knows the function is virtual
, therefore it knows it has to call it through the virtual function table.
Upvotes: 2
Reputation: 726479
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.
Upvotes: 7