FAQ 21.15 Should a class with virtual functions have at least one non-inline virtual function?

It is a good idea.

If the base class has a virtual destructor, the destructor in the derived class will also be virtual, and, unless specified otherwise, will be inline.

The safest bet is to give every derived class at least one non-inline virtual function (assuming the base class has a virtual destructor). To show how subtle this can be, consider this trivial example.

 class Base { public:   virtual ~Base() throw(); }; class Derived : public Base {   // ... }; int main() { } 

Even though no Base or Derived objects are created, the preceding example will fail to link on many systems. The reason is that the only virtual function in class Derived is inline (Derived::~Derived() is a synthesized inline virtual function), so the compiler puts a static copy of Derived::~Derived() into the current source file. Since this static copy of Derived::~Derived() invokes Base::~Base() (see FAQ 20.05) the linker will need a definition of Base::~Base().

Adding a non-inline virtual function to a derived class (for example, thisDoesNothing()) eliminates the linker errors for that derived class, because the compiler puts the (only) copy of the magical stuff into the source file that defines the non-inline virtual function.

 class Derived2 : public Base { public:   //... private:   virtual void thisDoesNothing() throw(); }; // This goes in exactly one source file, such as Derived2.cpp void Derived2::thisDoesNothing() throw() { } 


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