FAQ 33.11 How can final classes and final member functions improve performance?

By eliminating the overhead associated with dynamic binding.

Final member functions can be called using full qualification ("::"). This allows the compiler to employ static binding, thereby reducing or even eliminating the cost of dynamic binding. If care is taken, this can allow virtual functions to be inlined, thus effectively eliminating the CPU overhead associated with the added flexibility brought by virtual functions. An example follows.

 class Shape { public:   virtual void draw() const throw() = 0;   virtual ~Shape() throw(); }; Shape::~Shape() throw() { } class Circle : public Shape { public:   /*final*/ void draw() const throw(); }; inline void Circle::draw() const throw()             <-- 1 {   // ... } void sample(Circle& c) throw() {   c.Circle::draw(); } 

(1) Note the inline even though it is virtual

The full qualification (that is, the Circle:: part of c.Circle::draw()) is safe because final member functions are never overridden in derived classes. Function sample(Circle&) would also be safe if class Circle were final, since all members of a final class, including Circle::draw(), are implicitly final.

Note that it is (hopefully) somewhat uncommon to have lots of functions that take derived class references, such as sample(Circle&) in the example (see FAQ 33.14).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net