--- Mer 2/9/09, Gopi Krishna Komanduri <[email protected]> ha scritto:

Da: Gopi Krishna Komanduri <[email protected]>
Oggetto: Re: [c-prog] some basic queries about polymorphism
A: [email protected]
Data: Mercoledì 2 settembre 2009, 20:09

class Base
{
public:
    virtual void show()
     {
     }
}

int main()
{
  Base obj;
  obj.show() // I think complite time polymorphism comes here. 

  Base *obj = new Base()
  obj->show() // RUN Time
}

> Please correct me if I am wrong . I would like to know why this happens > 
> like so.

Polymorphism only happens when access to a memberfunction is done via pointers 
or references and _never_ when direct access is used.

If you use only the Base class in your example then there is no difference 
between the two methods because you always call Base::show() but there is a 
_big_ difference in _how_ the function gets called.

If you know a little assembly then write the example above and use the 
'assembly-only' flag of GCC:

$ gcc -S -o test.S test.cpp

and look at the assembler code in the 'test.S' file.

You may notice that every instance of a class which has virtual functions has 
an hidden data member that is a pointer to the virtual table of the constructed 
class. In our example the virtual table only contains one pointer:

_vptr.Base
----------
the pointer to Base::show()


In the first call - obj.show() - the assembly code is like this:

    call 0x8048532


A direct call to the address of Base::show() function is done because the 
variable 'obj' was declared as Base type
This happens even if the actual object is of a derived type.

Using pointer's access is totally different - obj->show(). This is the assembly 
code on my machine :


    mov  eax,-10[%ebp]
    mov  ebx,eax[2]
    mov  edx,ebx
    call %edx

Firt, the code loads some CPU registers with the pointer to the virtual table, 
this pointer is stored in the _real_ object so if it is a derived class then 
the virtual table of the derived class is loaded.
The EDX register is loaded with the pointer to the show() function of the 
virtual table.
Finally an _indirect_ call is done to the address pointed to by EDX.

In other words, when access to memberfunctions is done directly then the type 
of the declared variable states the address of the function called.
When access is done using pointers then the function called depends on the 
_actual_ type of the object not on the type of the declared variable used for 
accessing it.



Luciano


















      

Reply via email to