Pergunta

I know that for any class that has a virtual function or a class that is derived from a class that has a virtual function, the compiler does two things. First, it creates a virtual table for that class and secondly, it puts a virtual pointer (vptr) in the base portion for the object. During runtime, this vptr gets assigned and starts pointing to the correct vtable when the object gets instantiated.

My question is that where exactly in the instantiation process does this vptr gets set? Does this assignment of vptr happens inside the constructor of the object of before/after the constructor?

Foi útil?

Solução

This is strictly Implementation dependent.

For Most compilers,

The compiler initializes this->__vptr within each constructor's Member Initializer list.

The idea is to cause each object's v-pointer to point at its class's v-table, and the compiler generates the hidden code for this and adds it to the constructor code. Something like:

Base::Base(...arbitrary params...)
   : __vptr(&Base::__vtable[0])  ← supplied by the compiler, hidden from the programmer
 {

 }

This C++ FAQ explains a gist of what exactly happens.

Outras dicas

The pointer to the vtable is updated on entry to each constructor in the hierarchy and then again on entry of each destructor. The vptr will start pointing to the base class, and then will be updated as the different levels are initialized.

While you will read from many different people that this is implementation defined, as it is the whole choice of vtables, but the fact is that all compilers use vtables, and once you choose a vtable approach, the standard does mandate that the type of the runtime object is that of the constructor/destructor being executed, and that in turn means that whatever the dynamic dispatch mechanism is, it has to be adjusted as the construction/destruction chain is traversed.

Consider the following code snippet:

#include <iostream>

struct base;
void callback( base const & b );
struct base {
   base() { callback( *this ); }
   ~base() { callback( *this ); }
   virtual void f() const { std::cout << "base" << std::endl; }
};
struct derived : base {
   derived() { callback( *this ); }
   ~derived() { callback( *this ); }
   virtual void f() const { std::cout << "derived" << std::endl; }
};
void callback( base const & b ) {
   b.f();
}
int main() {
   derived d;
}

The standard mandates that the output of that program is base, derived, derived, base, but the call in callback is the same from all the four calls to the function. The only way that it can be implemented is by updating the vptr in the object as construction / destruction progresses.

This msdn article explains it in great detali

There it says :

"And the final answer is... as you'd expect. It happens in the constructor."

If I might add, right at the beginning of the constructor, before any other code you might have in your constructor gets executed.


But be careful, let's say you have the class A, and a class A1 derived from A.

  • If you create a new A object, the vptr will be set right at the beginning of the constructor of the A class
  • But if you create a new object A1:

"Here's the entire sequence of events when you construct an instance of class A1:

  1. A1::A1 calls A::A
  2. A::A sets vtable to A's vtable
  3. A::A executes and returns
  4. A1::A1 sets vtable to A1's vtable
  5. A1::A1 executes and returns "

In the body of the constructor, the virtual functions may be called, so, if the implementation used a vptr, that vptr is already set.

Note that the virtual functions called in a ctor are the ones defined in that constructor's class and not the ones possibly overridden by a more derived class.

#include <iostream>

struct A
{
    A() { foo (); }
    virtual void foo () { std::cout << "A::foo" << std::endl; }
};

struct B : public A
{
    virtual void foo () { std::cout << "B::foo" << std::endl; }
};


int
main ()
{
    B b;      // prints "A::foo"
    b.foo (); // prints "B::foo"
    return 0;
}

While it's implementation dependent, it would actually have to happen before the body of the constructor itself is evaluted since you are allowed, per the C++ spec (12.7/3), to access non-static class methods via the this pointer in the constructor body ... therefore the vtable would have to be setup before the body of the construtor is called, otherwise calling virtual class methods via the this pointer would not work correctly. Even though the this pointer and the vtable are two different things, the fact that the C++ standard allows the this pointer to be used in the body of a constructor demonstrates how the compiler must implement the vtable for standards-compliant uses of the this pointer to work correctly, at least from a timing perspective. If the vtable were initialized during or after the constructor body is called, then using the this pointer to call virtual functions inside the body of the constructor or pass the this pointer to functions that depend on dynamic dispatch would be problematic and create undefined behavior.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top