Skip to content

In-Class Exercise

10. Practice

motto


Zeroth task!

Before solving the tasks, download the starter code — we will work by extending it!

Starter code

starter.cpp


  1. Replace the raw Cowbell pointer in the starter Cow class with a shared_ptr<Cowbell>!
    • Do not use raw pointers anywhere!
    • Remove any parts of the code that are no longer needed!
  2. The farmers have developed a cowbell whose Ringtone can be changed. Its implementation is found in the SmartCowbell class.
    • Can the shared_ptr<Cowbell> member of the Cow class point to a SmartCowbell object?
      If yes, will it behave as a SmartCowbell when calling its makeSound method?
    • Try passing different cowbells in main!
  3. Retrieve the SmartCowbell set in the previous task from one cow, and assign it to another cow as well!
    Print the use_count of the shared_ptr before and after the assignment!
    • What might cause the numbers to differ from the expected values (1 and 2)?
    • Examine the return type of the cow’s getCowbell method!
  4. Change the ring-count of one cow’s cowbell!
    • What do you observe when the other cow rings its cowbell?
    • What is the root cause of the problem? (shared_ptr)
  5. Ensure that using smart pointers, each cow has its own unique cowbell!
    • Solve this using unique_ptr!
  6. Check why the setCowbell function does not compile!
    • Why might this be the case? What could be the solution?
  7. Try copying a cow!
    • What might be the reason for the observed behavior?
  8. Implement deep-copying using the clone approach!
    • Use only unique pointers!

Got stuck or couldn’t follow the class?! Or do you just want to review?
Here is one possible solution to the tasks!

Solution from class

solution.cpp



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