Skip to content

In-Class Exercise

8. Practice

The aliens have found what they were looking for on Earth, and now is the time to start copying the selected Earthlings so they can leave our Galaxy and return to their home planet with the replicas. motto


Task Zero!

Before starting the exercises, download the initial code — we’ll extend this as we go!

Initial code

starter.cpp


  1. Take a look at the Animal class! Is there anything that needs fixing?
    • Fix it!
  2. Implement the appropriate copy constructor(s) and assignment operator(s)!
  3. Examine the lifetime of the cow object in the main function in the given initial code! Fix the code if necessary!
  4. Call the listen() method of the Saucer in main! What happens if we delete Mary the cow before the listening?
  5. Modify the code so that the Saucer stores copies of the abducted animals!
    • Try reallocating each animal using new.
    • Test your code! Check the output of the listen() function!
    • Any possible improvements?
  6. Implement the following methods:
    • Animal* clone() const method in the Animal class
      • It should return a new Animal object using the copy constructor.
    • Cow* clone() const method in the Cow class
      • It should return a new Cow object using the copy constructor.
    • Carp* clone() const method in the Carp class
      • It should create a new Carp object using the copy constructor.
    • Should clone be virtual?
  7. Modify the abduct() function. The clone method of the parameter should be called!
    • What will be the output of listen()?
  8. Implement the destructor, copy constructor, and assignment operator for Saucer!

Got stuck or couldn’t follow the class? Or just want to review?
Here’s one possible solution to the exercises!

In-class solution

solution.cpp



Last update: 2025-11-27
Created: 2025-11-27