Skip to content

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.

motto

  1. Let's create a Cow class! It should have the following data members:

    • name: string
    • weight: unsigned
  2. 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 to const. What do you observe?
    • Create a global (outside the Cow class) function called addName! It should do two things: print to cout that "Name set", and return the string "Riska"!
    • Use this function to set the name data member!
  3. 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!
  4. 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"!
  5. Refactor the default constructor to call the two-parameter constructor (delegating constructor)!

  6. Create a print method in the Cow class! This method should be responsible for printing the cow’s data. Replace the existing print statements with a call to this print method!

  7. Create another global method called cowPrinter! It should take a cow as a parameter and call the cow's print method!

    • Change the parameter type to a cow reference!
    • Try modifying the cow’s weight inside cowPrinter! What do you observe after cowPrinter 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

solution.cpp



Last update: 2025-09-04
Created: 2025-09-04