Re: Why can't 'vptr' be static?
irotas ha scritto:
I was reading over the C++ FAQ item here:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.4
In that FAQ, the author explains that the 'vtable' is a static table -
that is, there's one per class that needs a virtual table.
The FAQ warns that this topic is "entirely compiler-dependent". Well,
the warning is a bit of an understatement, as C++ has no concept of
vtable at all, compilers are allowed to use any other means as long as
they provide the correct behaviour.
However, he explains, there is a non-static 'vptr' pointer to the
vtable as a hidden member variable of all classes (that need a virtual
table).
Naively, since all instantiations of a class will have the exact same
'vptr', it seems like it would make sense to have a single static
'vptr' per class.
Of course, this isn't really possible, else they would have done it
already. However, I'm at a loss as to why exactly it isn't possible.
Could someone please enlighten me?
Consider this:
struct Base
{
virtual void f();
};
struct Derived
{
virtual void f();
};
int main()
{
Base* pb1 = new Base();
Base* pb2 = new Derived();
pb1->f(); // shall call Base::f()
pb2->f(); // shall call Derived::f(), not Base::f()
}
How does the line pb1->f() calls Base::f() while pb2->f() calls
Derived::f()? The two lines are perfectly identical from the "static"
point of view, so they must rely on some information stored in a
*non-static* member of the objects in order to determine their
most-derived type. If the hidden vptr were static you would still need
to have a non-static member, so it's much easier to make the vptr itself
non-static.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]