As far i know when we make a function virtual in base class a pointer which can be referred as vptr is created by the compiler and a vtable which holds the entrys of virtual function which are latest version for this class in case of overridden function .and the vptr points to the vtable. classes that are derived from the base class have the same story , they have a pointer vptr and own vtable which holds the entrys of the latest virtual function . To understand my question follow the code
#include <iostream>
using namespace std;
class base
{
public:
virtual void display(void)
{
cout << "base\n";
}
};
class derived : public base
{
public:
void display(void)
{
cout << "derived\n";
}
};
int main(void)
{
base *p;
base ob1;
derived ob2;
p=&ob2;
p->display();//my point starts from here
p->base::display();
}
In the above code the statement p->display(); it does make sense that the object p points call the vptr of this class and look up for display function from the vtable and bind it. But i am not understanding that how would i describe the statement p->base::display(); in terms of vptr and vtable .how the compiler will bind the display function of base class version .As there would be no display function of base class version in the vtable of the derived class. If anything my knowing would wrong here , please tell me what the right is . And if i am right then tell me how will i describe the p->base::display(); statement with the logic i described p->display(); statement
But i am not understanding that how would i describe the statement p->base::display(); in terms of vptr and vtable .how the compiler will bind the display function of base class version
Vptr is not involved in that call in any way. Vptr is only used in virtual dispatch.
The use of explicit scope resolution in that call means that you are using static dispatch. You are saying, call the function base::display
regardless of the dynamic type of the object argument.
Virtual dispatch is a form of runtime polymorphism and a key feature of object oriented programming. When a function call is dispatched virtually, the call is dispatched to the most derived override of the function in the inheritance hierarchy, which depends on the dynamic type of the object.
A function call dispatched statically in contrast is dispatched using compile time name resolution, which is not affected by the dynamic type of the object. This is the default type of dispatch that is used in C++. It is also typically the only type of dispatch in imperative, non-object oriented languages such as C.
Virtual dispatch can only be used with virtual functions. Virtual dispatch is typically implemented using a virtual function table (vtable) and virtual function pointer (vptr).