virtual re-open

Discussion in 'C++' started by puzzlecracker, May 3, 2005.

  1. At what point does an object (an instance of the class that has virtual
    functions) put proper function in the vtable. I dont see it how it is
    run-time binding.

    Base *d=new Derived (...); // let's say the both have function
    // getName() declared as virtual and
    //defined in the both class.

    Obviously 'd' is a pointer to a an object of class D, but d considers
    it as a base class and when virtual function is invoked it consults
    vtable. But placing the address of the function to vtable is done at
    compile time


    Thanks
     
    puzzlecracker, May 3, 2005
    #1
    1. Advertising

  2. puzzlecracker

    Rolf Magnus Guest

    puzzlecracker wrote:

    > At what point does an object (an instance of the class that has virtual
    > functions) put proper function in the vtable.


    The compiler does that at compile-time.

    > I dont see it how it is run-time binding.
    >
    > Base *d=new Derived (...); // let's say the both have function
    > // getName() declared as virtual and
    > //defined in the both class.
    >
    > Obviously 'd' is a pointer to a an object of class D, but d considers
    > it as a base class and when virtual function is invoked it consults
    > vtable. But placing the address of the function to vtable is done at
    > compile time


    The vtable is per-class, not per-object. The object only holds a pointer to
    its class's vtable. So when creating a Derived, that pointer is set to
    Derived's vtable. If you now call a virtual member function through a
    pointer to Base, the vtable pointer - which is at the same place in Derived
    as in Base - is followed. In this case, it leads to the vtable of Derived.
    Then the pointer to the virtual function to be called is looked up and the
    function called through it.

    Btw: This is actually not required by the standard, though there seems to be
    no known implementation that doesn't use vtables for virtual function
    calls.
     
    Rolf Magnus, May 3, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Derek Simmons
    Replies:
    0
    Views:
    806
    Derek Simmons
    Aug 1, 2004
  2. Jéjé
    Replies:
    2
    Views:
    401
    Jéjé
    Nov 30, 2005
  3. while_1
    Replies:
    2
    Views:
    632
    Roedy Green
    Jun 25, 2004
  4. Jim Fischer
    Replies:
    3
    Views:
    441
    Jim Fischer
    Jul 31, 2003
  5. Michael Winter
    Replies:
    9
    Views:
    621
    Michael Winter
    Sep 24, 2003
Loading...

Share This Page