Article 27 - C++ Virtual Tables

In C++, there is an entity known as the virtual table. This table is used for runtime (dynamic) function pointers and is required for inheritance.

A virtual table is automatically generated (by the compiler) whenever a class declares a function virtual (any derived class of this base class will also contain a virtual table). Recall, in C++, a function is declared virtual if a derived class is permitted to override it. This virtual table is stored in the program code, and an associated pointer, known as the virtual table pointer (vtptr) is used to dereference the runtime object's function. Often, the virtual table sits above the program code, but below the heap.

The virtual table allows the virtual table pointer to point to the correct function to invoke during runtime. For example, if a base class declares the function overwrite() as virtual, then a virtual table is generated in this class. Any derived class, whether it overrides this function will also contain a virtual table. During runtime, the virtual table pointer points to the current derived class (if the object's pointer is any ancestor's class), and selects the appropriate function. In this example, since the derived class did not override the function, then the virtual table (of the dervied class) will have an entry that references the base class's function instead. On the other hand, if the derived class did override the virtual function, then the virtual table pointer will be pointing to the derived class's function instead.

Always make sure to declare your class's destructor virtual if there is ever a chance of subtyping that base class; otherwise, you risk not invoking the derived class's destructor if the pointer is of base class.

Comments (19)

Posted by anonymous - social bookmarks at Thursday, March 14, 2013 6:00 AM

uU1g33 I appreciate you sharing this article.Much thanks again. Cool.

Posted by anonymous - cipro at Friday, March 15, 2013 10:20 AM

I truly appreciate this blog article.Really thank you! Really Cool.

Posted by anonymous - generic viagra without a prescription at Friday, March 15, 2013 11:59 AM

I value the blog post.Really thank you!

Posted by anonymous - generic cialis online at Friday, March 15, 2013 1:38 PM

I really enjoy the blog post. Want more.

Posted by anonymous - 20mg levitra at Friday, March 15, 2013 3:18 PM

Looking forward to reading more. Great blog post. Much obliged.

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.