In-Class Exercise
2. Practice¶
The cows of the planet are peacefully grazing their favorite grass under the sunny, cloudless skies, completely unaware that the aliens — the Axerwálians — are already preparing their saucers for a cow-napping invasion.

-
Let's create a
Cowclass! It should have the following data members:name: stringweight: unsigned
-
Instantiate a cow in
main, i.e., create a cow object!- Print its data members! How can this be done (in OOP and less OOP ways)?
- Change the
namedata member toconst. What do you observe? - Create a global (outside the
Cowclass) function calledaddName! It should do two things: print tocoutthat "Name set", and return the string"Riska"! - Use this function to set the name data member!
-
Create a two-parameter constructor in the
Cowclass!- Add a print line at the very beginning of the constructor:
"Cow parameterized constructor: <name> <weight>" - After the print, set the weight using the "Java-style" approach! Run the program and observe the order of print outputs!
- Try to set the name value from the parameter as well. What happens?
- Rewrite the member initialization using an initializer list! Observe the order of the print outputs!
- Add a print line at the very beginning of the constructor:
-
Create a default (parameterless) constructor! The default values of the data members should be:
- name:
Mooo - weight:
125 - Add a print statement to the start of the constructor:
"Cow default constructor"!
- name:
-
Refactor the default constructor to call the two-parameter constructor (delegating constructor)!
-
Create a
printmethod in theCowclass! This method should be responsible for printing the cow’s data. Replace the existing print statements with a call to thisprintmethod! -
Create another global method called
cowPrinter! It should take a cow as a parameter and call the cow'sprintmethod!- Change the parameter type to a cow reference!
- Try modifying the cow’s weight inside
cowPrinter! What do you observe aftercowPrinterfinishes? - Change the parameter type to a constant cow reference!
- Fix the code accordingly!
Stuck or couldn’t follow along in class? Or just want to review? We’ll show you one possible solution to the tasks!
In-Class Exercise Solution
Created: 2025-11-27