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() { return "Lap lap lap."; }
virtual const char * bark() { return "Woof!"; }
virtual ~Dog() = default;
};
class Chihuahua : public Dog {
public:
virtual const char * bark() { return "¡Yip!"; }
};
Dog *koko = new Chihuahua;
cout << koko->drink() << '\n' << koko->bark();
delete koko;
Lap lap lap.
¡Yip!
Mixins
- Mixins also use inheritance, and could certainly be considered
an is-a relationship, but don’t think about it that way.
- Focus on the base class providing methods
to the derived class.
class PowerRing {
public:
auto zap() { return "green beam"; }
};
class GreenLantern : public PowerRing { };
GreenLantern john_stewart;
cout << john_stewart.zap();
green beam
- Don’t think of John as being a power ring.
Instead, he uses the abilities that the power ring gives him.
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
- Beginning programmers put everything in one giant main().
- Experienced programmers break up a big program into several functions.
- This helps to make each individual function manageable.
- Beginning O-O programmers put everything into
one giant class.
- Experienced programmers, break up a big class into several classes.
- This helps to make each individual class manageable.
- Classes can be combined in several ways. Has-a and is-a are two
common methods. Mixins are a certain type of is-a.