Item 28. Controlled Polymorphism

I l @ ve RuBoard

Difficulty: 3

Is-A polymorphism is a very useful tool in OO modeling. But, sometimes, you may want to restrict which code can use certain classes polymorphically. This Item gives an example and shows how to get the intended effect.

Consider the following code:

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

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.

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