Download C++ FAQs (Second Edition) 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
A final member function should not be marked with the virtual keyword
even if it happens to be an override of a virtual function. If the final member
function is not an override of a virtual from a base class, the easiest way to
make it final is to not use the virtual keyword.
Caution should be used before declaring a member function to be final.
Nonetheless, doing so is sometimes useful, as demonstrated in FAQ 33.12.
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()
// Note the inline even though it is virtual
{
// ...
}
void sample(Circle& c) throw()
{
c.Circle::draw();
}
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.
356