In-Class Exercise
10. Practice¶

Zeroth task!
Before solving the tasks, download the starter code — we will work by extending it!
Starter code
- Replace the raw
Cowbellpointer in the starterCowclass with ashared_ptr<Cowbell>!- Do not use raw pointers anywhere!
- Remove any parts of the code that are no longer needed!
- The farmers have developed a cowbell whose
Ringtonecan be changed. Its implementation is found in theSmartCowbellclass.- Can the
shared_ptr<Cowbell>member of theCowclass point to aSmartCowbellobject?
If yes, will it behave as aSmartCowbellwhen calling itsmakeSoundmethod? - Try passing different cowbells in
main!
- Can the
- Retrieve the
SmartCowbellset in the previous task from one cow, and assign it to another cow as well!
Print theuse_countof 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
getCowbellmethod!
- 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)
- Ensure that using smart pointers, each cow has its own unique cowbell!
- Solve this using
unique_ptr!
- Solve this using
- Check why the
setCowbellfunction does not compile!- Why might this be the case? What could be the solution?
- Try copying a cow!
- What might be the reason for the observed behavior?
- 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
Last update:
2025-11-27
Created: 2025-11-27
Created: 2025-11-27