[LC++]virtual functions

Torsten Rennett Torsten at Rennett.de
Thu Oct 28 20:03:02 UTC 2004


On Donnerstag, 28. Oktober 2004 11:48, choube mehul wrote:
> oh a big mistake. sorry.
> now look at the following:
>
> code sample:
>
> class base
> {
> virtual void print (void)
> {
> cout << "base"<<endl;
> }
> };
>
> class derived : public base
> {
> void print (void)
> {
> cout << "derived" << endl;
> }
> };
>
> int main (int argc, char argv)
> {
> derived d;
>
> return 0;
> }
>
> now the ques. is whether virtual table will be
> created?

yes.

> 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.

> there is no base class pointer scenario
> even then virtual table will be created?
> if yes why?

Potentially there may be another module like this:

void printObj(base *ptr)
{
  ptr->print();
}

The main module, where object 'd' is created, will not know if this happens 
or not (i.e. if another module like the above will be linked in later or 
not). So, to be sure, in the main module the virtual table has to be 
created.

On the other hand, a really clever compiler sees all of the simple main() 
function and might recognize that a function like printObj() is never 
called (even if linked in). So it might optimize the vtable away.

If you really want to know what your compiler is doing in such cases, just 
compile your little test program and have a look at the object code (*.o) 
with nm(1).


Torsten

-- 
Ingenieurbuero RENNETT      -- innovative Software-Entwicklung --
Torsten Rennett                    http://www.RENNETT.de
Ludwig-Thoma-Weg 14         E-Mail:            Torsten at Rennett.de
D-85551 Heimstetten         Telefon:            +49 89 904 805 38




More information about the tuxCPProgramming mailing list