In-Class Exercise
4. Practice¶
The aliens want to perfect the cow-abduction modules of their flying saucers. As a first step, they increase the suction power and range. However, an unintended side effect is that the sheepdogs guarding the cows are also getting sucked up. But they absolutely do not want to abduct dogs. Help them fix the bug!

Zeroth Task!
Before starting the exercises, download the starter code - we’ll be working by extending it!
Starter Code
-
Write a
FlyingSaucerclass! It should have avectordata member for storing cows, initially empty. -
Add an
abduct()function to theFlyingSaucerclass, which takes a cow as a parameter and adds it to the vector only if its weight is greater than 60. -
Add another
abduct()function to theFlyingSaucerclass, which takes a sheepdog as a parameter and throws astd::runtime_errorto signal that dogs must not be abducted! The error message should be the dog's name. -
Duplicate the
abduct()functions in theFlyingSaucerclass by renaming them tooperator<<:void operator<<(const Cow& c)void operator<<(const Sheepdog& d)- Try using them in
main!
-
Implement the abduction logic with the
+=operator as well. Test it inmain!- Try chaining both
+=and<<operators: - Example:
saucer << cow1 << cow2; - What happens? Fix the code so that chaining works with the
<<operator, but not with+=!
- Try chaining both
-
We want to be able to compare two flying saucers to determine which is smaller. A flying saucer is smaller than another if it holds fewer cows.
- Implement this using two helper functions called
isLessThan():- One version should be inside the
FlyingSaucerclass. - The other version should be a global function outside the class.
- One version should be inside the
- Try renaming one of them to
operator<! - What happens if you rename both?
- Implement this using two helper functions called
-
In
main, create asetof cows and asetof flying saucers, and add some elements to each!set<Cow> cows;set<FlyingSaucer> saucers;- What do you observe?
- "Fix" the
Cowclass so that it can be stored in aset! First compare cows by their name, and if those are equal, compare by weight.
-
Try reversing the comparison operator (
<) logic in theFlyingSaucerclass. What order do you get in theset? -
Implement the
==and!=operators for comparing two cows. Try them out! -
Implement the
==operator between anunsignedinteger and aCow. The equality should be true if the weight of the cow matches theunsignedvalue.- How many functions are needed?
- Should they be inside or outside the
Cowclass?
-
Make the
Cowclass convertible to anunsignedvalue! Return the cow’s weight.
Stuck or couldn’t follow everything in class? Or just want to review? Here’s one possible solution for the exercises!
In-Class Solution
Created: 2025-11-27