A better method that's a bit more clear, and doesn't rely on pointer
to virtual members
is to use a public interface to private virtual (similar to the
Template design pattern).
e.g.:
class C {
private:
virtual void vf();
public:
void f();
// remainder redacted
};
void C::f()
{
vf();
}
void (C::*pf)() = &C::f;
> void (C::*pf)() = &C::f;- Hide quoted text -
>
> - Show quoted text -
struct Base
{
virtual void f();
};
struct Derived : Base
{
void f();
};
void test(Base *bp)
{
void (Base::*pmf)() = &Base::f;
(bp->*pmf)();
}
When you call test with a pointer to a Base object it calls Base::f.
When you call test with a pointer to a Derivd object it calls
Derived::f. Try it.
> With the implementation you have given, there is increased overhead,
> if I understand correctly my jumptable under your suggestion will be
> setup to non-virtual functions, which in turn will call virtual
> functions, which in turn will cause vtable lookup (3 levels of
> indirections).
>
If you're concerned about speed, measure. Calling a virtual function
through a pointer to member function can be quite complicated, depending
on the class hierarchy.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of
"The Standard C++ Library Extensions: a Tutorial and Reference"
(www.petebecker.com/tr1book)
Yes, member function pointers fully take into account dynamic binding
and will call the proper function. (AFAIK that's the reason why member
function pointers usually have double the size of a regular function
pointer.)
> b)Is there a performance penalty with this implementation (going
> through 2 lookups one for jump table and then for vtable)?
Virtual function calls always have a small penalty compared to regular
function calls. In most cases it's so small that it doesn't matter in
practice.
Calling a function (virtual or otherwise) through a pointer to member
function is not the same as calling a function by name through a pointer
or reference to an object. It can be much more complicated: the runtime
code has to match the type of the object with the class of the
pointed-to member function and sort out any necessary adjustments.