Boost logo

Boost :

From: George A. Heintzelman (georgeh_at_[hidden])
Date: 2002-02-13 10:26:21


> >By 'final', I mean a way to mark a class 'final' like in Java to prevent
> >others from deriving from that class. A simple solution of this is
> >something like this:
>
> I've wanted 'final' before, but for a reason this doesn't address: optimization. Within a 'final' class, the compiler
> can statically bind all virtual member function references, since it's knows that there can be no more-derived class
> that it doesn't know about.
>
> That, unfortunately, doesn't appear to have a solution without a language extension or very sophisticated whole-program
> optimization.

There is a solution if you wrap the virtual call in non-virtual calls.
This is a little bit of a pain, plays a few games with
implementation-hiding, and it's possibly a little dangerous if used
around unskilled maintenance programmers, so beware the dangers of
premature optimization. That said, here's how to do it:

class Base {
  virtual void doF();
public:
  void F() { doF(); }; // Non-virtual call
};

class Derived:public base {
  virtual void doF(); // final override...
public:
  void F() { Derived::doF(); }

};

The explicit call to Derived::doF() enables the compiler to optimize
F() calls for Derived and, as a bonus, any further derived classes of
Derived. The class itself need not be final, though the override must
be. Unfortunately, AFAIK, there's no way of preventing further derived
classes from overriding doF(), which would lead to some very bizarre
behavior. Hence the danger. But in certain kinds of hierarchies with
certain kinds of needs, it can be valuable.

A language extension to mark virtual overrides as final, ie not virtual
for any more-derived classes, would IMHO be welcome as a safer way of
doing this. Hey! How about using the static keyword for this? :) It's
probably the only context where static is illegal right now, we need to
do something about that.

George Heintzelman
georgeh_at_[hidden]


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk