How to access vtable from this pointer in c++ program. vtable is per class basis. All objects of a class share the same vtable. Each object of a class contains the address of its vtable in the beginning of the it’s address.  The first two or four byte of the object contains address of vtable.

Let us see below code

using namespace std;

class Base {
	virtual void Hello()
		cout <<"Hello\n";
	void foo()
	  // address of object
	  int *vptr = (int *)this;

	  //address of VTABLE
	  vptr = (int *)*vptr;

	  //call Hello()
      ( (void (*)()) vptr[0])();


int main() {
	Base obj;;
	return 0;
  • When a class has any virtual function then compiler inserts a vptr pointer. vptr points to the VTABLE.
  • VTABLE stores the addresses of functions to be called at runtime.
  • To access virtual pointer (vptr) , we need to access the address of vptr.

Related Contents to follow