Skip to content

Extra Exercises

Home Practice Exercises I.

  1. Create a Vehicle class that has a private string fuel data member with a public getter!

    Solution
  2. Add a move() function to the vehicle that prints that the vehicle is moving and also displays the fuel type!

    Solution
  3. Create a Car class that inherits from Vehicle and has a private unsigned speed data member with a public getter!

    Solution
  4. The Car should override the move() function. Instead of the original message, it should print that the car is moving at [speed] km/h and consumes [fuel]!

    Solution
  5. Create a Ship class that inherits from Vehicle and has a private float speed data member with a public getter!

    Solution
  6. The Ship should also override the move() function. Instead of the original message, it should print that the ship is moving at [speed] knots and consumes [fuel]!

    Solution
  7. Write a function that takes a Vehicle type object and calls its move() method. Then, call it with one instance of each of the created classes!

    Solution

Home Practice Exercises II.

  1. Create an Animal class!

    • The only attribute of the animal is whether it is a herbivore (herbivore: bool). Write a parameterized constructor for the class that prints to the standard output: "animal created"!
    • Write a destructor that prints: "animal deleted"!
  2. Create a Cat class that publicly inherits from the Animal class!

    • The Cat should have a name, which must be given at creation!
    • The herbivore data member should be set to false.
    • The constructor and destructor should both print that the Cat was created/deleted, including its name!
  3. Add a void eat() method to the Animal class!

    • If the animal is a herbivore, it should print: "grazes"; otherwise, it should print: "hunts"!
    • In the Cat class, this method should print: "[cat name] cat hunts mice"!
  4. Create a function that takes an Animal type and calls its eat() method!

    • What happens if you use different parameter passing methods (by value, by reference, by pointer)?
  5. Dynamically instantiate a Cat, but make the static type of the variable Animal! Then delete it. What do you observe?
    (For this part of the exercise, you might not yet have all the required knowledge from the previous labs. It’s worth looking ahead to the next exercises!)

    Solution

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