Thursday, August 03, 2006

VTable

How did the vtable works when there is virtual function in base class, and same function name is derived class?

For each class which has at least 1 virtual function, the compiler build a virtual table with the addresses of those virtual functions.

In the constructor, each object gets a Vptr, which is a pointer to the VTable.

In inheritance, the base class's constructor is called first. It creates the Vptr and initializes it to the Base VTable.

The derived class constructor is called then, and updates the Vptr to point the Derived VTable.

The final state of the Vptr is determined by the constructor who called last.

When a Base pointer points to a derived object and calls a virtual method, the compiler translate this call to something like:

pBase -> Vptr -> right place in the VTable -> right method.

----
a pure virtual declaration:
virtual void f() = 0;

By doing this, you tell the compiler to reserve a slot for a function in the VTABLE, but not to put an address in that particular slot. Even if only one function in a class is declared as pure virtual, the VTABLE is incomplete.

If the VTABLE for a class is incomplete, what is the compiler supposed to do when someone tries to make an object of that class? It cannot safely create an object of an abstract class, so you get an error message from the compiler. Thus, the compiler guarantees the purity of the abstract class. By making a class abstract, you ensure
that the client programmer cannot misuse it. (update: Jan. 31, 08, thinkinginc++)

No comments:

Post a Comment