Final Practise Question OOP
Final Practise Question OOP
1. Create a class called Invoice that a hardware store might use to represent an invoice for
an item sold at the store. An Invoice should include four data members—a part number
(type string), a part description (type string), a quantity of the item being purchased
(type int) and a price per item (type int). [Note: In subsequent chapters, we’ll use
numbers that contain decimal points (e.g., 2.75)—called floating-point values—to
represent dollar amounts.] Your class should have a constructor that initializes the four
data members. Provide a set and a get function for each data member. In addition,
provide a member function named getInvoiceAmount that calculates the invoice
amount (i.e., multiplies the quantity by the price per item), then returns the amount as
an int value. If the quantity is not positive, it should be set to 0. If the price per item is
not positive, it should be set to 0. Write a test program that demonstrates class Invoice’s
capabilities.
2. Create a class called Rectangle with two data members: length and width (both of type
float). The class should have a constructor that accepts two parameters and initializes
the data members. Ensure that the values for length and width are greater than 0; if not,
set them to 1. Provide getter and setter methods for both data members. Add member
functions calculateArea and calculatePerimeter to compute and return the area and
perimeter of the rectangle, respectively. Write a program to test the Rectangle class.
3. Create an Account class that a bank might use to represent customers’ bank accounts.
Include a data member of type int to represent the account balance. [Note: In subsequent
chapters, we’ll use numbers that contain decimal points (e.g., 2.75)—called floating-
point values—to represent dollar amounts.] Provide a constructor that receives an initial
balance and uses it to initialize the data member. The constructor should validate the
initial balance to ensure that it’s greater than or equal to 0. If not, set the balance to 0
and display an error message indicating that the initial balance was invalid. Provide
three member functions. Member function credit should add an amount to the current
balance. Member function debit should withdraw money from the Account and ensure
that the debit amount does not exceed the Account’s balance. If it does, the balance
should be left unchanged and the function should print a message indicating "Debit
amount exceeded account balance." Member function getBalance should return the
current balance. Create a program that creates two Account objects and tests the
member functions of class Account.
4. Create a class called BankAccount with the following attributes: account_number (type
int), account_holder (type string), and balance (type float). Write a constructor to
initialize these attributes. Provide setter and getter methods for each attribute. Add
methods deposit to add money to the balance and withdraw to subtract money from the
balance (ensure that the withdrawal does not cause the balance to go negative). Write a
test program to demonstrate the capabilities of the BankAccount class.
5. Create a class that includes a data member that holds a “serial number” for each object
created from the class. That is, the first object created will be numbered 1, the second
2, and so on. To do this, you’ll need another data member that records a count of how
many objects have been created so far. (This member should apply to the class as a
whole; not to individual objects. What keyword specifies this?) Then, as each object is
created, its constructor can examine this count member variable to determine the
appropriate serial number for the new object. Add a member function that permits an
object to report its own serial number. Then write a main() program that creates three
objects and queries each one about its serial number. They should respond I am object
number 2, and so on. 9.
6. Create a class called Date that includes three pieces of information as data members—
a month (type int), a day (type int) and a year (type int). Your class should have a
constructor with three parameters that uses the parameters to initialize the three data
members. For the purpose of this exercise, assume that the values provided for the year
and day are correct, but ensure that the month value is in the range 1–12; if it isn’t, set
the month to 1. Provide a set and a get function for each data member. Provide a
member function displayDate that displays the month, day and year separated by
forward slashes (/). Write a test program that demonstrates class Date’s capabilities.
7. Create an Account class that a bank might use to represent customers’ bank accounts.
Include a data member of type int to represent the account balance. Provide a
constructor that receives an initial balance and uses it to initialize the data member. The
constructor should validate the initial balance to ensure that it’s greater than or equal to
0. If not, set the balance to 0 and display an error message indicating that the initial
balance was invalid. Provide three member functions. Member function credit should
add an amount to the current balance. Member function debit should withdraw money
from the Account and ensure that the debit amount does not exceed the Account’s
balance. If it does, the balance should be left unchanged and the function should print
a message indicating "Debit amount exceeded account balance." Member function
getBalance should return the current balance. Create a program that creates two
Account objects and tests the member functions of class Account.
8. Create a fraction class. Member data is the fraction’s numerator and denominator.
Member functions should accept input from the user in the form 3/5, and output the
fraction’s value in the same format. Another member function should add two fraction
values. Write a main() program that allows the user to repeatedly input two fractions
and then displays their sum. After each operation, ask whether the user wants to
continue.
9. While exercising, you can use a heart-rate monitor to see that your heart ratestays within
a safe range suggested by your trainers and doctors. According to the American Heart
Association (AHA), the formula for calculating your maximum heart rate in beats per
minute is 220 minus your age in years. Your target heart rate is a range that is 50–85%
of your maximum heart rate. Create a class called HeartRates. The class attributes
should include the person’s first name, last name and date of birth (consisting of
separate attributes for the month, day and year of birth). Your class should have a
constructor that receives this data as parameters. For each attribute provide set and get
functions. The class also should include a function getAge that calculates and returns
the person’s age (in years), a function getMaxiumumHeartRate that calculates and
returns the person’s maximum heart rate and a function getTargetHeartRate that
calculates and returns the person’s target heart rate. Since you do not yet know how to
obtain the current date from the computer, function getAge should prompt the user to
enter the current month, day and year before calculating the person’s age. Write an
application that prompts for the person’s information, instantiates an object of class
HeartRates and prints the information from that object—including the person’s first
name, last name and date of birth—then calculates and prints the person’s age in
(years), maximum heart rate and target-heart-rate range.
10. A health care issue that has been in the news lately is the computerization of health
records. This possibility is being approached cautiously because of sensitive privacy
and security concerns, among others. [We address such concerns in later exercises.]
Computerizing health records could make it easier for patients to share their health
profiles and histories among their various health care professionals. This could improve
the quality of health care, help avoid drug conflicts and erroneous drug prescriptions,
reduce costs and in emergencies, could save lives. In this exercise, you’ll design a
“starter” HealthProfile class for a person. The class attributes should include the
person’s first name, last name, gender, date of birth (consisting of separate attributes
for the month, day and year of birth), height (in inches) and weight (in pounds). Your
class should have a constructor that receives this data. For each attribute, provide set
and get functions. The class also should include functions that calculate and return the
user’s age in years, maximum heart rate and target-heart-rate range (see Exercise 3.16),
and body mass index (BMI; see Exercise 2.30). Write an application that prompts for
the person’s information, instantiates an object of class HealthProfile for that person
and prints the information from that object—including the person’s first name, last
name, gender, date of birth, height and weight—then calculates and prints the person’s
age in years, BMI, maximum heart rate and target-heart-rate range. It should also
display the “BMI values” chart from Exercise 2.30. Use the same technique as Exercise
3.16 to calculate the person’s age.
11. In ocean navigation, locations are measured in degrees and minutes of latitude and
longitude. Thus if you’re lying off the mouth of Papeete Harbor in Tahiti, your location
is 149 degrees 34.8 minutes west longitude, and 17 degrees 31.5 minutes south latitude.
This is written as 149°34.8’ W, 17°31.5’ S. There are 60 minutes in a degree. (An older
system also divided a minute into 60 seconds, but the modern approach is to use decimal
minutes instead.) Longitude is measured from 0 to 180 degrees, east or west from
Greenwich, England, to the international dateline in the Pacific. Latitude is measured
from 0 to 90 degrees, north or south from the equator to the poles. Create a class angle
that includes three member variables: an int for degrees, a float for minutes, and a char
for the direction letter (N, S, E, or W). This class can hold either a latitude variable or
a longitude variable. Write one member function to obtain an angle value (in degrees
and minutes) and a direction from the user, and a second to display the angle value in
179°59.9’ E format. Also write a three-argument constructor. Write a main() program
that displays an angle initialized with the constructor, and then, within a loop, allows
the user to input any angle value, and then displays the value. You can use the hex
character constant ‘\xF8’, which usually prints a degree (°) symbol.
12. Create a class called ship that incorporates a ship’s number and location. Use the
approach of a “serial number” for each ship object created from the class. That is, the
first object created will be numbered 1, the second 2, and so on to number each ship
object as it is created. Use two variables of the angle class from above question to
represent the ship’s latitude and longitude. A member function of the ship class should
get a position from the user and store it in the object; another should report the serial
number and position. Write a main() program that creates three ships, asks the user to
input the position of each, and then displays each ship’s number and position.
13. Use the fraction class in a program that generates a multiplication table for fractions.
Let the user input a denominator, and then generate all combinations of two such
fractions that are between 0 and 1, and multiply them together. Here’s an example of
the output if the denominator is 6:
14. Create a class called time that has separate int member data for hours, minutes, and
seconds. One constructor should initialize this data to 0, and another should initialize it
to fixed values. Another member function should display it, in 11:59:59 format. The
final member function should add two objects of type time passed as arguments. A
main() program should create two initialized time objects (should they be const?) and
one that isn’t initialized. Then it should add the two initialized values together, leaving
the result in the third time variable. Finally it should display the value of this third
variable. Make appropriate member functions const
15. You are building an e-commerce system where a customer can add items to their
shopping cart. Each item in the cart is represented by a Product class, which contains a
name, price, and a quantity for the product. The shopping cart should allow the user to
add multiple products and calculate the total value of the cart. Implement the Cart class
where the user can add Product objects to the cart. Implement a method to compute the
total price of all items in the cart. Consider implementing both shallow and deep copy
functionality for Cart—one where items in the cart are shared and one where each cart
item is copied independently when cloned.
16. You are working on an order management system. An order contains a Customer and a
list of OrderItem objects, which represent individual products within an order.
Implement a method in the Order class that allows for cloning an order. Implement both
shallow and deep copy methods for this order, ensuring that if a deep copy is made,
changes to the OrderItem objects in one order do not affect the OrderItem objects in
another order.
17. In a library system, you have a Book class that contains the title, author, and publication
date, and each Book has a reference to a Publisher object. The Publisher object contains
the publisher’s name and the location. Implement a method in the Library class to track
which books are being borrowed. Implement a method to clone a Library that will create
deep copies of all Book objects (including their Publisher objects). When a book is
borrowed, the library's internal reference to the book should remain unchanged.
Consider the edge case when a book is borrowed multiple times by different customers.
18. A hotel reservation system tracks rooms available for booking. Each Room has a unique
roomNumber, a price, and a reference to a Customer. Implement a method to clone a
Room object where the room's booking status is shallowly copied, but the Customer
object is deep copied so that a new Customer object is associated with the cloned room.
Implement a method that allows for the cloning of an entire hotel’s room list while
maintaining the integrity of the Room objects and their associated Customer objects.
19. Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent
toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps
track of the number of cars that have gone by, and of the total amount of money
collected. Model this tollbooth with a class called tollBooth. The two data items are a
type unsigned int to hold the total number of cars, and a type double to hold the total
amount of money collected. A constructor initializes both of these to 0. A member
function called payingCar() increments the car total and adds 0.50 to the cash total.
Another function, called nopayCar(), increments the car total but adds nothing to the
cash total. Finally, a member function called display() displays the two totals. Make
appropriate member functions const. Include a program to test this class. This program
should allow the user to push one key to count a paying car, and another to count a
nonpaying car. Pushing the Esc key should cause the program to print out the total cars
and total cash and then exit.
20. In a project management system, you are handling a Project object that has a list of
tasks. Each task is represented by a Task class with attributes such as taskId, taskName,
assignedTo (a TeamMember), and status. Write methods to deep copy a Task where
the TeamMember object associated with the task is also copied. Implement a method
in the Project class that performs a shallow copy of the project, where the list of tasks
is copied by reference.
21. A financial portfolio contains a list of Investment objects. Each Investment has a name,
amount, and dateAcquired. The Portfolio class has methods to clone the portfolio and
its investments. Implement a method to perform a deep copy of the Portfolio, where
each Investment object inside the portfolio is copied individually. Implement a shallow
copy method, where the Investment objects are shared between the original and the
copied portfolio, and changes made to the investment objects affect both portfolios.
22. A recipe management system allows users to create recipes. Each recipe contains a list
of Ingredient objects. Each Ingredient has a name, quantity, and unit. Implement a
method to clone a Recipe object, where the ingredients are deeply copied so that each
new recipe object gets independent copies of the ingredients. Provide a method that
makes a shallow copy of a recipe, where the original and the copied recipe share
references to the same Ingredient objects.
23. In a music streaming application, users can create and share playlists. A Playlist object
contains a list of Song objects. Each Song has a title, artist, and duration. Implement a
method in the Playlist class to perform a shallow copy of the playlist where the Song
objects are not copied, but merely referenced. Provide a deep copy method where each
song is cloned independently, so that modifications to a song in one playlist don’t affect
other playlists with the same song.
24. In a document editing system, a Document class has content that is a collection of
Paragraph objects. Each Paragraph contains text, and you can create different versions
of the document. Implement a method that allows the document to be cloned. In the
cloned document, each paragraph should be deeply copied so that changes made to the
paragraphs in one document do not reflect in the other. Add a feature to the document
editor to shallow copy the document, where only references to paragraphs are copied.
25. In a university enrollment system, students enroll in multiple courses. Each Student
object has a list of Course objects, and each Course has a course name and a list of
enrolled students. Implement a deep copy method in the Student class where each
course is independently copied. Each Student should have their own course objects that
do not affect other students who are enrolled in the same course. Implement a shallow
copy of the Student class, where the Course objects are shared between the students. If
one student changes the course details, it should affect all students enrolled in that
course.