Re: design problem with inheritance
On 24 ao=FBt, 16:21, alessio211734 <alessio211...@yahoo.it> wrote:
You would need to make flapwings public.
Yes this is the lack I see with this design, I should do public
methods in the class Duck to access them from a external class.
There is an alternative, make FlyBehavior a friend of Duck and code
protected class member function in FlyBehavior for accessing duck's
private members. That way, only class inheriting FlyBehavior can
access those members.
If you are afraid of cluttering the interface, you can also declare a
protected nested class.
Example:
#include <iostream>
class duck;
class FlyBehavior
{
public: virtual void fly( duck* d) = 0;
protected:
friend class duck; // duck can declare DuckFlyBehavior a friend;
class DuckFlyBehavior;
};
class duck
{
public:
duck(FlyBehavior& f):_fb(&f){}
void fly(){ _fb->fly(this); }
protected:
friend class FlyBehavior::DuckFlyBehavior; // DuckFlyBehavior can
call FlapWings
void FlapWings(){ std::cout<<"flap flap\n"; }
private:
FlyBehavior* _fb;
};
struct FlyBehavior::DuckFlyBehavior
{
// break encapsulation of duck
static void FlapWings(duck* d){
d->FlapWings();
}
};
class Fly: public FlyBehavior
{
public:
virtual void fly(duck *d) { DuckFlyBehavior::FlapWings(d); }
};
int main()
{
Fly fly;
duck donald(fly);
donald.fly();
}
--
Michael