Inclusion polymorphism (part 1)

This lesson contains approximately 20 minutes of video content.

Name hiding

Function overriding and virtual functions

Questions

In the code that follows, we define a Duck that willdelegate its quacking behavior to another class, instead of using behaviors that are defined in the base class and overridden in the derived class. That is, we are going say that a Duck HAS-A QuackBehavior and we will provide that behavior by composing a Duck with the right QuackBehavior object. Study the following code before proceeding:
duck.hpp
#ifndef DUCK_HPP
#define DUCK_HPP
#include "quack_behavior.hpp"

#include <string>

class Duck {
public:
  std::string PerformQuack() { return quack_behavior_->Quack(); };
  void SetQuackBehavior(QuackBehavior *qb) { quack_behavior_ = qb; };
  virtual ~Duck() { delete quack_behavior_; }

protected:
  Duck() : quack_behavior_(new NoQuack) {}
  Duck(QuackBehavior *qb) : quack_behavior_(qb) {}

private:
  QuackBehavior* quack_behavior_;
};

class MallardDuck : public Duck {
public:
  MallardDuck() : Duck(new QuietQuack) {}
};

class RubberDuck : public Duck {
public:
  RubberDuck() {}
};

#endif
quack_behavior.hpp
#ifndef QUACKBEHAVIOR_HPP
#define QUACKBEHAVIOR_HPP
#include <string>

struct QuackBehavior {
  virtual std::string Quack() = 0;
};

struct LoudQuack : public QuackBehavior {
  std::string Quack() { return "QUACK!";}
};

struct QuietQuack : public QuackBehavior {
  std::string Quack() { return "Quack";}
};

struct NoQuack : public QuackBehavior {
  std::string Quack() { return "Silence";}
};

#endif