Solution

I l @ ve RuBoard

graphics/bulb.gif

Consider the following code:

  class Base   {   public:   virtual void VirtFunc();   // ...   };  class Derived : public Base { public:   void VirtFunc();   // ... }; void SomeFunc( const Base& ); 

The reason why all code can use Derived objects polymorphically where a Base is expected is because Derived inherits publicly from Base (no surprises here).

If, instead, Derived inherited privately from Base , then almost no code could use Derived s polymorphically as Base s . The reason for the almost is that code with access to the private parts of Derived can still access the private base classes of Derived and can therefore use Derived s polymorphically in place of Base s. Normally, only the member functions of Derived have such access. However, we can use C++'s friend feature to extend similar access to other outside code.

Putting the pieces together, we get the following:

There are two other functions . The goal is to allow f1() to use Derived objects polymorphically where a Base is expected, yet prevent all other functions (including f2() ) from doing so .

  void f1()   {   Derived d;   SomeFunc( d ); // works, OK   }   void f2()   {   Derived d;   SomeFunc( d ); // we want to prevent this   }  

Demonstrate how to achieve this effect .

The answer is to write:

 class Derived : private Base { public:   void VirtFunc();   // ...   friend void f1(); }; 

This solves the problem cleanly, although it does give f1() greater access than f1() had in the original version.

I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

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