Extra Exercises
Home Practice Exercises I.¶
-
Create a
Vehicleclass that has a privatestring fueldata member with a public getter!Solution
- Code: Exercise 1
-
Add a
move()function to the vehicle that prints that the vehicle is moving and also displays the fuel type!Solution
- Code: Exercise 2
-
Create a
Carclass that inherits fromVehicleand has a privateunsigned speeddata member with a public getter!Solution
- Code: Exercise 3
-
The
Carshould override themove()function. Instead of the original message, it should print that the car is moving at [speed] km/h and consumes [fuel]!Solution
- Code: Exercise 4
-
Create a
Shipclass that inherits fromVehicleand has a privatefloat speeddata member with a public getter!Solution
- Code: Exercise 5
-
The
Shipshould also override themove()function. Instead of the original message, it should print that the ship is moving at [speed] knots and consumes [fuel]!Solution
- Code: Exercise 6
-
Write a function that takes a
Vehicletype object and calls itsmove()method. Then, call it with one instance of each of the created classes!Solution
- Code: Exercise 7
Home Practice Exercises II.¶
-
Create an
Animalclass!- 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"!
- The only attribute of the animal is whether it is a herbivore (
-
Create a
Catclass that publicly inherits from theAnimalclass!- The
Catshould have a name, which must be given at creation! - The
herbivoredata member should be set tofalse. - The constructor and destructor should both print that the
Catwas created/deleted, including its name!
- The
-
Add a
void eat()method to theAnimalclass!- If the animal is a herbivore, it should print: "grazes"; otherwise, it should print: "hunts"!
- In the
Catclass, this method should print: "[cat name] cat hunts mice"!
-
Create a function that takes an
Animaltype and calls itseat()method!- What happens if you use different parameter passing methods (by value, by reference, by pointer)?
-
Dynamically instantiate a
Cat, but make the static type of the variableAnimal! 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
- Code: Practice Exercise Set
Created: 2025-11-27