Virtual Pointer:
Virtual pointer is implicitly added (by Compiler) to each object of a class which contains virtual function or which inherits a class containing virtual function.
To access VTABLE we need its address.Compile r stores this address in Virtual pointer.This Virtual pointer is stored in first 2 bytes of an object memory(Physical ).
So, we need an integer pointer to access first two bytes of object memory.Followin g code accesses the VTABLE of a class using integer pointer :
- This Virtual pointer points to VTABLE (Virtual Table) of that class. VTABLE is static member of such class.
- VTABLE stores the addresses of functions to be invoked on polymorphic reference(At runtime).
To access VTABLE we need its address.Compile r stores this address in Virtual pointer.This Virtual pointer is stored in first 2 bytes of an object memory(Physical ).
So, we need an integer pointer to access first two bytes of object memory.Followin g code accesses the VTABLE of a class using integer pointer :
Code:
#include<iostream>
#include<conio.h>
using namespace std;
class Base
{
public:
virtual void display() //virtual function
{
cout<<"\nBase : display()..";
}
virtual void goodMorning() //virtual function
{
cout<<"\nBase : Good morning..";
}
};
class Derived:public Base
{
public:
void display() //virtual by default
{
cout<<"\nDerived : display()..";
}
//Derived does not override goodMorning()
};
int main()
{
Derived d1;
int *vptr=(int *)&d1; //vptr points to Derived object
//Virtual pointer is stored in first 2 bytes of object
vptr=(int *)*vptr; //copy virtual pointer (first 2 bytes) into vptr
//Now content of vptr is nothing but address of VTABLE
//call display()
((void (*)()) *vptr )();
//*vptr is address of first virtual function in VTABLE viz. display()
//and we cast VPTR to a function pointer
++vptr; //move 2 bytes ahead
//access second function in Derived's VTABLE viz.Base::goodMorning()
((void (*)()) *vptr )();
getch();
return 0;
}
Comment