Vptr & ptable run time execution


I'm not able to understand the internal implementation of the virtual table and prt concept.

class Base

virtual void get(){ cout<<"Base:;Get"<<endl;}

class Der : public Base
void get() { cout<<"Der::Get"<<endl;}

Base* b = new Der();

This is the example.

Address as 1000 & 2000
For Base Class:
vptr(1000) -----> vTable(2000)-> get()

In Derived this vtable n vptr is been inherited.

when b->get is called, then it is referring to vptr means then it should call base of get() but how the pointer is getting changed and the call is been made to execute the derived class function?
Where the derived class function in the vtable is getting stored??

Can anyone explain in detail on the run time changes that are happening?


Unlike many modern languages with quite flexible object models, C++ implements one vtable per class. The vtables contents are fixed up by the time the program starts running.

So in your example, there are two vtables, one for Base, one for Der. Both vtables have one entry.

The vtable of Base has the address of Base::get.

The vtable of Der has the address of Der::get.

You create an instance of Der and place it in b.

When you call b->get(), the indirection causes the actual function address to be looked in the vtable of Der, whcih gives you Der::get. So Der::get() is called.

I'm not sure what all that vptr(1000) -----> vTable(2000)-> get() stuff is about.

but how the pointer is getting changed
Nothing is getting changed, it's just looking up a table that's been previously prepared.
Last edited on
Topic archived. No new replies allowed.