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
FlyingSaucer
class! It should have avector
data member for storing cows, initially empty. -
Add an
abduct()
function to theFlyingSaucer
class, 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 theFlyingSaucer
class, which takes a sheepdog as a parameter and throws astd::runtime_error
to signal that dogs must not be abducted! The error message should be the dog's name. -
Duplicate the
abduct()
functions in theFlyingSaucer
class 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
FlyingSaucer
class. - 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 aset
of cows and aset
of flying saucers, and add some elements to each!set<Cow> cows;
set<FlyingSaucer> saucers;
- What do you observe?
- "Fix" the
Cow
class 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 theFlyingSaucer
class. What order do you get in theset
? -
Implement the
==
and!=
operators for comparing two cows. Try them out! -
Implement the
==
operator between anunsigned
integer and aCow
. The equality should be true if the weight of the cow matches theunsigned
value.- How many functions are needed?
- Should they be inside or outside the
Cow
class?
-
Make the
Cow
class convertible to anunsigned
value! 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-09-04