Preets wrote:
Is the v-table, that gets generated by the compilation of a class
having virtual functions, global ? Why and how ?
First of all, vtables are an implementation artifact - C++ doesn't
require them. For example, virtual dispatch can be handled by the
compiler generating code that switches on the dynamic type of an object
(in some cases this is more efficient, since it allows inlining of
virtual calls).
Where the compiler uses them, vtables are generally global (though
dynamic linking can complicate this), since due to the one definition
rule, there can be only one definition of any particular type, so you
only need 1 vtable for each type that has virtual functions. Then, when
you create an object of a particular type, a pointer embedded in that
object is set to point to the relevant vtable.
As for the how, compilers tend to use heuristics to determine exactly
which translation unit (e.g. .o or .obj file) to put the vtable into.
This might be the .c file that contains the definition of the first
defined virtual function of the class, or if no such file exists (e.g.
because every function of the class is defined inline), the vtable is
emitted in every TU that needs it, and then they are coalesced at the
end by the linker.
Tom