1.

How Can Virtual Functions In C++ Be Implemented?

Answer»

When a class has at least one virtual function, the compiler builds a table of virtual function pointers for that class. This table, commonly called the v-table, contains an entry for each virtual function in the class. The constructor of the class is used to create this table. Each object of the class in memory includes a VARIABLE called the vptr, which points to the class's common vtbl. The _rst (which creates the vtable) is constructed by the base classes after the construction of the DERIVED classes. The derived class constructor overwrites the entries of the vtable, if its constructor overrides any virtual function of the base class. Therefore, you need not call every function from a constructor just to avoid the ERROR prone SCENARIO of calling the Base class constructor instead of the derived class constructor (which fails to set the entries of objects of vtable).

When a class has at least one virtual function, the compiler builds a table of virtual function pointers for that class. This table, commonly called the v-table, contains an entry for each virtual function in the class. The constructor of the class is used to create this table. Each object of the class in memory includes a variable called the vptr, which points to the class's common vtbl. The _rst (which creates the vtable) is constructed by the base classes after the construction of the derived classes. The derived class constructor overwrites the entries of the vtable, if its constructor overrides any virtual function of the base class. Therefore, you need not call every function from a constructor just to avoid the error prone scenario of calling the Base class constructor instead of the derived class constructor (which fails to set the entries of objects of vtable).



Discussion

No Comment Found