0% found this document useful (0 votes)
23 views4 pages

C++ OOP Problem Set Solutions

The document describes 7 problem sets involving object-oriented programming concepts in C++ such as classes, inheritance, polymorphism, templates, and exception handling. The first problem set involves implementing a shape hierarchy with classes for Rectangle and Circle that inherit from a base Shape class and demonstrate method overriding. The second problem set involves creating a BankAccount class to manage bank accounts with transactions like deposits and withdrawals using private members and friend functions. The third problem set involves creating an Employee class with private data members and public methods to initialize an object and adjust the salary based on criteria. The remaining problem sets involve managing student records using arrays and objects, calculating area using single inheritance, creating a generic Calculator class using templates

Uploaded by

kamruzaman shuvo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

C++ OOP Problem Set Solutions

The document describes 7 problem sets involving object-oriented programming concepts in C++ such as classes, inheritance, polymorphism, templates, and exception handling. The first problem set involves implementing a shape hierarchy with classes for Rectangle and Circle that inherit from a base Shape class and demonstrate method overriding. The second problem set involves creating a BankAccount class to manage bank accounts with transactions like deposits and withdrawals using private members and friend functions. The third problem set involves creating an Employee class with private data members and public methods to initialize an object and adjust the salary based on criteria. The remaining problem sets involve managing student records using arrays and objects, calculating area using single inheritance, creating a generic Calculator class using templates

Uploaded by

kamruzaman shuvo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Problem Set: OOP

1. Suppose, you are working on a software project that involves implementing a


geometry library in C++. The library should have a “Shape” class hierarchy to
represent different types of shapes, such as “Rectangle” and “Circle”. The “Shape”
class has the following specifications:
Member variables named “name” and “color”, Member functions named
setname(),setcolor(), displayinfo().
The derived class “Rectangle” inherited from “Shape” class has member variables
named “length” and “width” and member functions named “setDimensions()”,
“calculateArea()” (an override member function) Formula: length * width;
“displayInfo()”(an override member function). Similarly the derived class “Circle”
that has member variable “radius” and member functions
“setRadius()”,“calculateArea()” Formula: 3.14 * radius * radius; (an override member
function) “displayInfo()”(an override member function).
You need to demonstrate method overloading by implementing multiple versions of
the “calculateArea()” function in the “Shape” class based on the number and types of
parameters. Also, you need to demonstrate method overriding by overriding the
“calculateArea()” function in the “Rectangle” and “Circle” classes to provide their
specific implementation of calculating the area.
Once you have implemented the classes, you should create objects of each class, set
their attributes using the member functions, and call the “displayInfo()” function on
them to display the information of the shapes, including their calculated areas, on the
screen. Print appropriate messages to indicate which class's member function is being
called during the execution of the program. Apply polymorphism to the given criteria
by writing cpp code.

2. Problem Statement: Managing Bank Accounts

Develop a C++ program to manage bank accounts, utilizing friend functions and
constructors. The program should allow users to create and manipulate bank accounts,
including functionalities such as depositing and withdrawing funds, checking account
balances, and transferring funds between accounts. Implement a BankAccount class
with private attributes such as account number, account holder name, and balance.
Utilize a friend function to facilitate fund transfers between accounts while ensuring
appropriate access to private member variables. Additionally, design constructors to
initialize bank accounts with default or user-specified values. Develop a user-friendly
interface in the main program to interact with the bank account functionalities,
enabling users to perform transactions seamlessly. Ensure robust error handling to
manage invalid inputs and account operations effectively.
3. A class called Employee with private attributes for salary (double) and number of
hours worked per day (int). Define a constructor that initializes these attributes with
values passed as arguments.

i) Define a public method called 'getInfo()' that takes the salary and number of hours
of work per day of an employee as parameters and sets the corresponding attributes of
the Employee object.

ii) Define another public method called 'AddSal()' that adds $10 to the salary of the
employee if it is less than $500. This method should be called automatically as soon
as the Employee object is created.

iii) Define a third public method called 'AddWork()' that adds $5 to the salary of the
employee if the number of hours of work per day is more than 6.

In the main method, create an instance of the Employee class by passing the initial
salary and number of hours worked per day as arguments to the constructor. Then,
call the 'AddSal()' and 'AddWork()' methods on the Employee object to adjust the
salary based on the criteria specified. Finally, print out the final salary of the
employee to the console. Add error handling to the program by validating user input
for the salary and number of hours worked per day. Ensure that the program does not
crash or behave unexpectedly in case of invalid input. Demonstrate a C++ program
for the above scenario.

4. Problem Set: Managing Student Records

You are tasked with creating a program to manage student records using C++. Your
program should utilize an array of objects, constructors, and a friend function. Design a
solution that meets the following requirements:

Define a Student class to represent individual student records. Each student should have
the following attributes:
a. Student ID
b. Name
c. Grade
Implement a constructor for the Student class to initialize these attributes.

Create a friend function named displayStudentInfo that displays the information of a


student object.

Develop a main program that:


d. Creates an array of Student objects to store student records.
e. Initializes the array with data provided by the user or hardcoded values.
f. Calls the displayStudentInfo function to display the information of each
student.
Ensure proper validation of user inputs and error handling in the program.

5. Problem Statement: Area Calculation with Single Inheritance


You are required to develop a C++ program to calculate the area of different shapes using a
base class and single inheritance. Design a solution with the following specifications:
 Define a base class named Shape (Circle) with a function calculateArea()- for
circle. This class should have public member variables such as length, width, and
radius.
 Implement a derived class named Rectangle, inheriting from the Shape class. The
Rectangle class should have methods to set its dimensions and override the
calculateArea() function to calculate the area of a rectangle using the formula: length
* width.
 Develop a main program that:
 Creates an object of the Rectangle class.
 Sets its dimensions using user input or hardcoded values.
 Calls the calculateArea() function of the Rectangle class to calculate its area.
 Displays the calculated area on the screen.
 Test the program with various scenarios, including calculating the area of rectangles
with different dimensions.

6. Problem Statement: Generic Calculator


You are tasked with developing a generic calculator program using templates in C++.
Design a solution with the following specifications:
Define a template class named Calculator that supports arithmetic operations on
generic data types (integers, floating-point numbers, etc.). The Calculator class
should have methods to perform addition, subtraction, multiplication, and division
operations.
 Implement methods for each arithmetic operation within the Calculator class.
 Develop a main program that:
 Creates objects of the Calculator class for different data types (integers,
floating-point numbers, etc.).
 Calls the arithmetic operation methods on these objects to perform
calculations.
 Displays the results of each operation.
 Ensure proper validation of user inputs and error handling in the program.
 Test the program with various data types and arithmetic operations.

7. Design a C++ program that handles invalid input using try-catch blocks. Implement a
solution with the following specifications:

Define a function named calculateAverage() that calculates the average of two numbers. If
the user inputs a non-numeric value, the function should throw an exception.

Use a try-catch block within the calculateAverage() function to handle the following
exception:

If the user inputs a non-numeric value, throw an exception of type std::invalid_argument with
the message "Invalid input. Please enter numeric values".
Develop a main program that:

Prompts the user to input two numbers.


Calls the calculateAverage() function to calculate the average of the two numbers.
Handles any exceptions thrown by the calculateAverage() function and displays appropriate
error messages.
Displays the calculated average if no exceptions occur.

make a simple solution using cpp, try catch

Common questions

Powered by AI

Using friend functions for fund transfers between bank accounts in C++ poses challenges such as increased complexity and potential security risks since friend functions bypass access restrictions. However, the advantages include precise control over class internals, enabling direct manipulation of private data such as balances, which simplifies operations like transfers. Friend functions improve encapsulation by restricting access to only those functions explicitly declared as friends, maintaining data integrity while facilitating complex operations with minimal exposure of sensitive internals .

Using constructors in C++ to manage bank accounts impacts the initialization of account data by ensuring that all objects of the 'BankAccount' class start with valid state data. Constructors can set default values or accept user-specified parameters to initialize critical account attributes like account number, holder name, and balance immediately upon creation. This practice improves data integrity and minimizes errors by ensuring that objects are not left in an uninitialized or inconsistent state, thus enhancing the program's robustness .

Polymorphism in the implementation of a geometry library in C++ manifests through method overriding and method overloading within the 'Shape' class hierarchy. The base class 'Shape' provides a generic interface for setting and displaying object attributes, like 'name' and 'color,' and a method 'calculateArea()' which is overridden in derived classes such as 'Rectangle' and 'Circle'. Each derived class provides its specific implementation of the 'calculateArea()' method—'Rectangle' using the formula length * width, and 'Circle' using 3.14 * radius * radius, demonstrating polymorphic behavior via overrides. Additionally, method overloading is shown by creating multiple versions of 'calculateArea()' in 'Shape' to handle different parameters, enabling polymorphic function calls based on input types and numbers .

The 'displayStudentInfo' friend function enhances the management of student records in C++ by allowing external functions access to the non-public data of 'Student' class objects for display purposes. This approach facilitates the output of student data such as ID, name, and grade without violating encapsulation principles since it explicitly grants access to specific functions for necessary external operations. This functionality is particularly useful in managing records, where public data presentation is needed without exposing internal class logic .

Proper error handling in the C++ program that calculates the average of two numbers is achieved through the use of try-catch blocks, which manage exceptions by separating error detection from handling. When a non-numeric value is input, the 'calculateAverage()' function throws an exception of type std::invalid_argument with a descriptive error message. The try-catch mechanism captures this exception, allowing the program to handle the error gracefully, such as notifying the user with a specific message and avoiding crashes. By segregating exception detection and processing, the program maintains robustness and user-friendliness .

In managing bank accounts in C++, friend functions play a critical role in enhancing functionality by allowing access to the private member variables of classes. For instance, friend functions can facilitate fund transfers between accounts by directly manipulating private data like account balance and account number. This capability enables seamless access and modifications without exposing the class's internal structure to the outside world, thereby maintaining encapsulation while providing necessary functionality .

In the scenario of calculating areas with single inheritance in C++, overriding enhances functionality by enabling derived classes to provide specific implementations of methods defined in the base class. For instance, in a 'Shape' class hierarchy, a base class might define a generic 'calculateArea()' method. The 'Rectangle' derived class overrides this method to calculate the area using a formula specific to rectangles (length * width), offering a precise and optimized computation for rectangle objects while adhering to a common interface. This supports polymorphism, allowing base class pointers to invoke these overridden methods dynamically .

Automatic method calls in managing employee salaries play a significant role in ensuring that salary adjustments occur promptly upon object creation without additional manual intervention. Methods such as 'AddSal()' and 'AddWork()' are automatically triggered when an 'Employee' object is instantiated, applying conditional increments to salaries based on specific criteria such as base salary amount and working hours. This design ensures that all newly created objects meet predefined conditions immediately, simplifying the logic required for salary management and reducing the potential for oversight or errors in salary adjustments .

Method overloading and method overriding contribute to a flexible geometry library in C++ by enabling polymorphic behavior and versatile function implementations. Overloading allows multiple 'calculateArea()' functions in the 'Shape' class to handle varying input types and numbers, giving users different ways to compute an area based on available data. Overriding, on the other hand, provides specific implementations of 'calculateArea()' in derived classes like 'Rectangle' and 'Circle', ensuring that the correct formula (length * width for rectangles, π * radius^2 for circles) is applied. These features collectively promote code reuse, adaptability, and clarity, fostering a robust design .

Templates in C++ enhance the design of a generic calculator by providing the flexibility to perform arithmetic operations on various data types, such as integers and floating-point numbers, without code duplication. The template allows the 'Calculator' class to define methods for addition, subtraction, multiplication, and division that can be instantiated with different data types. This design improves code reusability and efficiency, as the same logic is applied universally across multiple types, reducing errors and maintenance costs .

You might also like