Skip to content

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!

motto


Zeroth Task!

Before starting the exercises, download the starter code - we’ll be working by extending it!

Starter Code

starter.cpp


  1. Write a FlyingSaucer class! It should have a vector data member for storing cows, initially empty.

  2. Add an abduct() function to the FlyingSaucer class, which takes a cow as a parameter and adds it to the vector only if its weight is greater than 60.

  3. Add another abduct() function to the FlyingSaucer class, which takes a sheepdog as a parameter and throws a std::runtime_error to signal that dogs must not be abducted! The error message should be the dog's name.

  4. Duplicate the abduct() functions in the FlyingSaucer class by renaming them to operator<<:

    • void operator<<(const Cow& c)
    • void operator<<(const Sheepdog& d)
    • Try using them in main!
  5. Implement the abduction logic with the += operator as well. Test it in main!

    • Try chaining both += and << operators:
    • Example: saucer << cow1 << cow2;
    • What happens? Fix the code so that chaining works with the << operator, but not with +=!
  6. 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.
    • Try renaming one of them to operator<!
    • What happens if you rename both?
  7. In main, create a set of cows and a set 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 a set! First compare cows by their name, and if those are equal, compare by weight.
  8. Try reversing the comparison operator (<) logic in the FlyingSaucer class. What order do you get in the set?

  9. Implement the == and != operators for comparing two cows. Try them out!

  10. Implement the == operator between an unsigned integer and a Cow. The equality should be true if the weight of the cow matches the unsigned value.

    • How many functions are needed?
    • Should they be inside or outside the Cow class?
  11. Make the Cow class convertible to an unsigned 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

solution.cpp



Last update: 2025-09-04
Created: 2025-09-04