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
Cow
class! 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
name
data member toconst
. What do you observe? - Create a global (outside the
Cow
class) function calledaddName
! It should do two things: print tocout
that "Name set", and return the string"Riska"
! - Use this function to set the name data member!
-
Create a two-parameter constructor in the
Cow
class!- 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
print
method in theCow
class! This method should be responsible for printing the cow’s data. Replace the existing print statements with a call to thisprint
method! -
Create another global method called
cowPrinter
! It should take a cow as a parameter and call the cow'sprint
method!- Change the parameter type to a cow reference!
- Try modifying the cow’s weight inside
cowPrinter
! What do you observe aftercowPrinter
finishes? - 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-09-04