Re: Something like a final method
* blargg:
=?ISO-8859-1?Q?Marcel_M=FCller?= wrote:
class Interface
{public:
virtual int GetStatus() = 0;
};
class AbstractBase : public Interface
{private:
int Status;
public:
virtual int GetStatus() { return Status; } // Never overridden
};
If I call GetStatus() through a pointer to AbstractBase (or any derived
class) the call cannot be inlined because it is a virtual function. Of
course, there is no other way when using a pointer to Interface. But
there are many calls via pointers to AbstractBase or some of the derived
classes. I would like to avoid these function calls since almost any
method of derived classes do it and the implementation of GetStatus is
really trivial.
Is there any better solution than renaming the method of Interface to
GetStatusByInterface() or something like that?
Use a forwarding function:
class Base {
public:
void f() { vf(); } // forward to virtual version
protected:
virtual void vf() = 0;
};
class Derived : public Base {
protected:
virtual void vf();
};
class Final : public Derived {
public:
void f() { Final::vf(); } // bypass virtual call
protected:
virtual void vf();
};
void user( Base& b, Derived& d, Final& f )
{
b.f(); // dynamic call to vf
d.f(); // dynamic call to vf
f.f(); // static call to Final::vf
}
Note how it's fine if you pass a Final via a Base&; you'll get a virtual
call. This is one instance where hiding a (non-virtual) base class
function isn't problematic.
In my earlier response I did it the other way, letting the virtual routine
forward to the non-virtual one; in terms of above code, vf() calling f().
I'm not sure if I thought it through at that time or simply grabbed back in my
hind-brain for a relevant pattern, but anyway there's a reason for that.
Namely, as indicated in your code, that any class that customizes the f()
calling vf() scheme must be (documented as or restricted to be) final, lest
someone derives a class DerivedFromFinal where f is again redefined. In that
case treating a DerivedFromFinal as a Final can invoke the wrong implementation
of f(). That's also /technically/ possible with calls going the other way, but
with f() calling vf() it's not apparent from the calling code whether o.f() is a
virtual call (safe) or non-virtual (unsafe) call, whereas with vf() calling f()
this is very clear: f() is always non-virtual, and vf() is always virtual.
Cheers, & hth.,
- Alf
PS: What complicates the whole thing is that no matter what, a derived class
that customizes things must define both f() and vf(). I see no way of ensuring
that. But then I'm a bit tired and perhaps there is a Way, who knows... :)
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!