I l @ ve RuBoard |
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 |