FAQ 29.04 What should a derived class do when it redefines some but not all of a set of overloaded member functions inherited from the base class?

graphics/new_icon.gif

The derived class should use the using syntax.

If the base class has an overloaded set of member functions and the derived class overrides some but not all of that set, the redefined member functions will hide the other overloads. The work-around is to use the using syntax. The following example shows class Base with two overloaded member functions called f.

 #include <iostream> using namespace std; class Base { public:   virtual ~Base()         throw();   virtual void f(int x)   throw();   virtual void f(float x) throw(); }; Base::~Base() throw() { } void Base::f(int x) throw() { cout << "Base::f(int)\n"; } void Base::f(float x) throw() { cout << "Base::f(float)\n"; } 

Now suppose the author of class Derived wants to override one of the two f() member functions. In this case the derived class should also say using Base::f; to avoid confusing users:

 class Derived : public Base { public:   virtual void f(int x) throw();   using Base::f;                                     <-- 1 }; void Derived::f(int x) throw() { cout << "Derived::f(int)\n"; } 

(1) This unhides f(float) (good!)

Because of the using Base::f; line in the derived class, f(float) is not hidden:

 void sample(Base& b, Derived& d) {   b.f(42);   d.f(42);   b.f(3.14f);   d.f(3.14f);                                        <-- 1 } int main() {   Derived d;   sample(d, d); } 

(1) This is not hidden (good!)

The output of this program demonstrates that the behavior depends on the type of the object, not the type of the reference:

 Derived::f(int) Derived::f(int) Base::f(float) Base::f(float) 

This guideline applies only to public inheritance; hiding base class member functions is fine for private or protected inheritance (see FAQ 37.01).



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