First, virtual functions and what you are proposing have different
semantics. If you need different behavior because you have different
types of objects, then it's highly unlikely that you can do better than
the compilers implementation of virtual functions. If you don't need
it, then just don't declare the function virtual.
And don't worry about the performance issue until you know it is one.
If, after getting the code to work, you do find performance issues due
to virtual function calls (usually because the compiler can't inline the
function, so you loose all of the optimizations which would follow
inlining), you can, punctually, avoid the virtual function cost if you
design the class correctly. Supposing the function in question is
f()
:
class Base
{
virtual void doF() = 0;
public:
void f() { doF(); }
};
class Derived : public Base
{
virtual void doF() { f(); }
public:
void f() { /* ... */ }
};
If you do this, and you have, for example, a tight loop where you're
constantly calling f()
on the same object, you can do something like:
void
tightLoop( Base& object )
{
Derived& o = dynamic_cast<Derived&>( object );
for ( /* ... */ ) {
o.f();
}
}
If you do this, of course, tightLoop
can only be called with an object
which is actually Derived
.