CS253: Software Development with C++

Fall 2022

Mixins

Show Lecture.Mixins as a slide show.

CS253 Mixins

🍨

Origin

The name “mixin” comes from adding various treats to ice cream, such as the McFlurry, Blizzard, or the ground-breaking research at Cold Stone Creamery.

Is-A

We know the is-a relationship, which comes from class inheritance:

class Dog {
  public:
    virtual const char * drink() const { return "Lap lap lap."; }
    virtual const char * bark() const { return "Woof!"; }
    virtual ~Dog() = default;
};

class Chihuahua : public Dog {
  public:
    virtual const char * bark() const { return "¡Yip!"; }
};

Dog *koko = new Chihuahua;
cout << koko->drink() << '\n' << koko->bark();
delete koko;
Lap lap lap.
¡Yip!

Mixins

class PowerRing {
  public:
    auto fly() const { return "whoosh"; }
    auto zap() const { return "pew pew"; }
};

class GreenLantern : public PowerRing { };

GreenLantern john;
cout << john.zap();
pew pew

Permissions

When writing a mixin class, it is common to take several steps to enforce that the class be used only as a mixin. Busybody? Yeah, kinda.

Constructors are protected
This ensures that the mixin class cannot be instantiated as a standalone object, because its ctors are not public. Instead, the protected ctors can only be called from methods of the derived class.
All methods are protected
The protected methods in the base class become private methods in the derived class. Therefore, they don’t become part of the public interface of the derived class, so the end user of the derived class can’t call them.

Usefulness