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
QDuck type, Q1

This question is graded, with maximum available score of 2 points.

There is a memory leak in our implementation of Duck. What line of the duck.hpp does the memory leak to occur on?

QDuck type, Q2

This question is graded, with maximum available score of 2 points.

What is the output of the following code snippet?

Duck* duck = new MallardDuck;
cout << duck->PerformQuack() << endl;
QDuck type, Q3

This question is graded, with maximum available score of 2 points.

What is the output of the following code snippet?

Duck* duck = new RubberDuck;
cout << duck->PerformQuack() << endl;
QDuck type, Q4

This question is graded, with maximum available score of 2 points.

What is the output of the following code snippet?

Duck* duck = new MallardDuck;
duck->SetQuackBehavior(new LoudQuack);
cout << duck->PerformQuack() << endl;