Welcome





Sunday, March 27, 2011

VIRTUAL TABLE

(Team 2 : 71,49,31,30,29,23,876).


          A  Virtual Table or Vtable is a mechanism used in a programming language to support dynamic dispatch or dynamic polymorphism where run time binding is done. The virtual table is a lookup table of functions used to resolve function calls in dynamic binding.
          Suppose a program contains several classes in an inheritance hierarchy i.e., a superclass and two subclasses and when the program calls the virtual function on a superclass pointer or any of the subclass pointers,the run time environment must be able to determine which implementation to call,depending on the actual type of the object that is pointed to. There are a variety of different ways to implement such dynamic dispatch,but the vtable solution is common among C++ and its related languages ,because it allows objects to use a different implementation simply by using a different set of method pointers.
        The virtual table is actually quite simple, though it’s a little complex to describe in words.

Implementation of VTABLE:


        Every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class. An object's dispatch table or vtable will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The virtual table is the same for all objects belonging to the same class, and is therefore typically shared between them. Objects belonging to type-compatible classes (for example siblings in an inheritance hierarchy) will have dispatch tables with the same layout: the address of a given method will appear at the same offset for all type-compatible classes. Thus, fetching the method's address from a given dispatch table offset will get the method corresponding to the object's actual class.
       The compiler also adds a hidden pointer to the base class, which we will call  as Vpointer or virtual pointer or vptr .vptr is set (automatically) when a class instance is created so that it points to the virtual table for that class. Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, vptr is a real pointer. Consequently, it makes each class object allocated bigger by the size of one pointer. It also means that vptr is inherited by derived classes, which is important.  The compiler also generates "hidden" code in the constructor of each class to initialize the vpointers of its objects to the address of the corresponding vtable.

No comments:

Post a Comment