[LC++]virtual functions

Paul Gearon gearon at ieee.org
Fri Oct 29 13:56:01 UTC 2004

On 29/10/2004, at 1:14 PM, choube mehul wrote:

>>> how many?
>> For each object of class base or class derived.
>> Here: one virtual table for object 'd'.
>>> one for base?
>>> and one for derived?
>> You have just one object 'd', so you have just one
>> virtual table within the
>> memory space of that object.
>     now if i add a pointer variable base *ptr
>     then will a additional virtual table be
>     created?
>     2 virtual tables one for ptr and another for
>     d?

No.  As Torsten said, you will only get a new virtual table with a new 

When you call the print() method on an object of type "derived" then 
you want the derived::print() method to be called, no matter what kind 
of compatible pointer you are using.

You can think of a virtual table as a form of indirection.  When a 
virtual table is present then the code will look inside the virtual 
table to find where this object's version of the method is, and then it 
will call the resulting pointer.  Having a virtual table lets an object 
say, "here is my own implementation of these methods".

If not for the virtual table then a pointer of type base* would always 
find the base::print() method, even if the object is of type "derived". 
  Calling a method on an object without a virtual table just goes to 
some fixed offset from the start of the object to find the method.

Paul Gearon

Software Engineer
Tucana Technologies

Catapultam habeo. Nisi pecuniam omnem mihi dabis, ad caput tuum saxum
immane mittam.
(Translation from latin: "I have a catapult. Give me all the money,
or I will fling an enormous rock at your head.")

More information about the tuxCPProgramming mailing list