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.
uU1g33 I appreciate you sharing this article.Much thanks again. Cool.
I truly appreciate this blog article.Really thank you! Really Cool.
I value the blog post.Really thank you!
I really enjoy the blog post. Want more.
Looking forward to reading more. Great blog post. Much obliged.