Q:

How virtual functions are implemented in C++?

0

How virtual functions are implemented in C++?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Virtual functions are implemented using a table of function pointers, called the VTABLE. There is one entry in the table per virtual function in the class. This table stores the address of the virtual function and it is created by the constructor of the class.

The object of the class containing the virtual function contains a virtual pointer (vptr) that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve the function address.

Due to the vptr, the size of the object increases by the size of the pointer. The vptr contains the base address of the virtual table in memory. Note that virtual tables are class-specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains.

At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.

Note: You should not call the virtual function in the constructor. Because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions For Experienced

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Is there a separate vtable for each object?... >>
<< When should I use references, and when should I us...