To accomplish late binding, the compiler creates this vtable table for each class that contains virtual functions and for the class derived from it. The compiler places the addresses of the virtual functions for that particular class in ‘vtable’. When virtual function call is made through a base-class pointer, the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the right function and causing late/dynamic binding to take place. class base { virtual void funct1(void); virtual void funct2(void); }; base b;
b.vptr = address of b.vtable
b.vtable[0]= &base::funct1() b.vtable[1]= &base::funct2()
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#include<iostream.h>
class Base { public: virtual void function1() {cout<<"Base :: function1()\n";}; virtual void function2() {cout<<"Base :: function2()\n";}; virtual ~Base(){}; }; class D1: public Base { public: ~D1(){}; virtual void function1() { cout<<"D1 :: function1()\n";}; }; class D2: public Base { public: ~D2(){}; virtual void function2() { cout<< "D2 :: function2\n";}; }; int main() { D1 *d = new D1;; Base *b = d; b->function1(); b->function2(); delete (b); return (0); } output: D1 :: function1() Base :: function2()
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Detail about How VPTR and Virtual table works |
Sunday, December 9, 2012
vtable and vptr in C++...
Subscribe to:
Post Comments (Atom)
-
Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency....go to below link... http://javapapers.co...
-
The stackalloc keyword C# has the stackalloc keyword which lets you force unmanaged type arrays to be allocated on the stack inside ...
No comments:
Post a Comment