He began to study design patterns and stalled in the first chapter of the book. The book is written for javistov, but I decided to translate the code in C ++.

#include <iostream> using namespace std; // interfaces class FlyBehavior { public: virtual void fly() = 0; }; class QuackBehavior { public: virtual void quack() = 0; }; // Flying class FlyWithWings : FlyBehavior { public: virtual void fly() { cout << "I'm flying" << endl; } }; class FlyNoWay : FlyBehavior { public: virtual void fly() { cout << "I can't fly" << endl; } }; // Quacking class Quack : QuackBehavior { public: virtual void quack() { cout << "Quack!" << endl; } }; class MuteQuack : QuackBehavior { public: virtual void quack() { cout << "Silence..." << endl; } }; class Squeak : QuackBehavior { public: virtual void quack() { cout << "Squeak!" << endl; } }; class Duck { public: FlyBehavior *flyBehavior; QuackBehavior *quackBehavior; virtual void display() = 0; virtual void performFly() { flyBehavior->fly(); } virtual void performQuack() { quackBehavior->quack(); } void swim() { cout << "All ducks float" << endl; } }; class MallardDuck : Duck { public: MallardDuck() { flyBehavior = new FlyWithWings(); quackBehavior = new Quack(); } virtual void display() { cout << "Typical mallard duck" << endl; } }; int main(int argc, char *argv[]) { Duck *pMallard = new MallardDuck(); pMallard->performFly(); pMallard->performQuack(); return 0; } 

I do not quite understand why it is impossible to translate from FlyBehavior* to FlyWithWings* . I know that you cannot create an object from an interface, but I convert it into an object of a certain class.

Compilation errors:

\ main.cpp: 97: error: C2243: type conversion: conversion "FlyWithWings *" to "FlyBehavior *" exists, but is not available

\ main.cpp: 98: error: C2243: type conversion: conversion "Quack *" to "QuackBehavior *" exists, but is not available

\ main.cpp: 110: error: C2243: type conversion: conversion "MallardDuck *" to "Duck *" exists, but is not available

  • one
    class Quack : public QuackBehavior . This requires public inheritance - andy.37
  • @ andy.37 really works. I thought that by default the public modifier inherits. From now on I will be more attentive. Thank you - Desmond Fox
  • Related question: stackoverflow.com/q/420635/176217 - αλεχολυτ

1 answer 1

As already noted in the commentary on the question, public inheritance is required for type conversion.

Record type:

 class D : B 

is equivalent to

 class D : private B 

To provide the possibility of casting, you must specify a public inheritance:

 class D : public B 

If struct used instead of class , then the default inheritance would be public and the specified problem did not arise.