0% found this document useful (0 votes)
6 views24 pages

OOP Homework 4

The document outlines the requirements for Homework 4 in the CS-1004 Object Oriented Programming course at FAST School of Computing for Spring 2025. It includes various tasks involving the creation of classes and inheritance structures, such as Account, Vehicle, Person, Publication, and more, each with specific attributes and methods to implement. Additionally, it emphasizes the importance of clean code, proper commenting, and submission guidelines.

Uploaded by

f240760
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)
6 views24 pages

OOP Homework 4

The document outlines the requirements for Homework 4 in the CS-1004 Object Oriented Programming course at FAST School of Computing for Spring 2025. It includes various tasks involving the creation of classes and inheritance structures, such as Account, Vehicle, Person, Publication, and more, each with specific attributes and methods to implement. Additionally, it emphasizes the importance of clean code, proper commenting, and submission guidelines.

Uploaded by

f240760
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
You are on page 1/ 24

CS-1004 Object Oriented Programming

Homework 4

Semester Spring 2025

FAST School of Computing

Instructions
1. Write clean and well-structured code with proper indentation.
2. Comment your code to explain key logic.
3. Ensure the code compiles and runs correctly before submission.
4. Upload your work before the deadline.
5. Submission will be Online on Google Classroom with Screenshots of running code in a word file.
6. Ask questions before the deadline if you have doubts.

🚀 Happy Coding!

------------------------------------------------------------------------------------------------------------------------------------------
1. Requirement:
Create a base class Account with data members:
accountNumber, balance.
Create a derived class SavingsAccount that adds an interest rate
and a function to apply interest. Use constructor for initialization.
-----------------------------------------------------------------------------------------------------------------------------------------

2. Requirement:
Create a base class Vehicle with brand and speed.
Create a derived class Car that adds model, and a function to
display full details.

Make sure:

 Base and derived class both have a display() function (check


method overriding).
 Demonstrate calling base class method using Car object.

------------------------------------------------------------------------------------------------------------------------------------------

3. Task:
1. Create a base class Person with:
o name (string), age (int)
2. Inherit Student from Person, and add:
o rollNo (int), degreeProgram (string)
3. Inherit GraduateStudent from Student, and add:
o researchTopic (string)
4. Input values for all fields using a GraduateStudent object and
display all details.
------------------------------------------------------------------------------------------------------------------------------------------

4. Task:
Create class Person with:

o name (string), age (int)

Create class Employee with:

o salary (float)

Create class Teacher that inherits from both Person and Employee.

Input and display all details of a Teacher.


------------------------------------------------------------------------------------------------------------------------------------------

5. Task:
1. Create a base class Publication with:
o title (string), price (float)
2. Inherit class Book from Publication and add:
o pageCount (int)
3. Inherit class Magazine from Publication and add:
o issueNumber (int)
4. Input and display data for both Book and Magazine objects.
------------------------------------------------------------------------------------------------------------------------------------------

6. Task:
1. Create base class Person with name and age.
2. Inherit class Student and class Employee from Person.
3. Create class TeachingAssistant that inherits from both Student
and Employee.
4. Use virtual inheritance to avoid duplication of Person.
5. Input all values and display them using a TeachingAssistant
object.
------------------------------------------------------------------------------------------------------------------------------------------

7. Scenario:
You are designing a library system that keeps track of books,
DVDs, and the users who borrow them.

Requirements:

 Create base class Item with itemID, title


 Derive Book and DVD classes from Item
 Create class User with userID, name
 Create class Transaction that:
o Has a Book and a User as data members
o Records issuing date
o Displays who borrowed which book

------------------------------------------------------------------------------------------------------------------------------------------

8. Scenario:
The university wants a system to store basic details of people, and
extended information for students and faculty.

Requirements:

 Create a base class Person:


o name, CNIC, email
 Derive Student from Person:
o rollNo, degree, CGPA
 Derive Faculty from Person:
o employeeID, designation, salary
 Input and display data for both a Student and a Faculty object.
------------------------------------------------------------------------------------------------------------------------------------------

9. scenario: You are developing a university system.

 Base Class: Person (private: name, protected: CNIC)


 Derived Class: Teacher (private: subject, salary)

Tasks:

 Use constructor chaining for both classes.


 Use accessors/mutators for private members.
 Add display() in derived class to show all information.
 In main(), create multiple Teacher objects using parameterized constructors and show
details.

Scenario: Build a media library system.

 Base: MediaFile (filename, size, type)


 Derived: VideoFile (resolution, duration)

Tasks:

 Use virtual display() in base, override in derived.


 Implement both default and parameterized constructors.
 Input details from user and display using base class pointer pointing to derived object.

------------------------------------------------------------------------------------------------------------------------------------------

10. Scenario: You are designing an employee payroll system.


 Employee → SalariedEmployee

Classes:

 Employee: empID, name (with getter/setters)


 SalariedEmployee: basicPay, bonus, totalSalary()

Tasks:

 Implement encapsulation (private with accessors).


 Use function overriding for showDetails().
 Create multiple objects, store them in array, and display all using loop.

------------------------------------------------------------------------------------------------------------------------------------------

11. Scenario: Banking System


 Account → LoanAccount

Requirements:

 Account: accountNo, holderName, balance


 LoanAccount: loanAmount, interestRate, calculatePayable()

Constraints:

 Apply constructor chaining.


 calculatePayable() returns total with interest.
 Use dynamic memory to store accounts and display payable info.

------------------------------------------------------------------------------------------------------------------------------------------

12. Write a program to demonstrate multiple inheritance with the following:


 Class X: a function void showX()
 Class Y: a function void showY()
 Class Z inherits both and adds its own function showZ()

Call all functions from a Z object.

------------------------------------------------------------------------------------------------------------------------------------------
13. In a travel booking system:
 BusInfo: routeNo, capacity
 DriverInfo: driverName, licenseNo
 BusDriver inherits both

Add constructor for all and a single display() method in derived class to show everything.

------------------------------------------------------------------------------------------------------------------------------------------

14. Scenario: Hospital system


 Person → Staff → Nurse

Tasks:

 Person: name, CNIC, private with getters


 Staff: dutyTime, salary, add protected method calculateBonus()
 Nurse: ward, patientsAssigned, override calculateBonus()
 Use vector<Nurse> and calculate average salary + bonus

------------------------------------------------------------------------------------------------------------------------------------------

15. Scenario: Academic system

 Base class Student, derived: Graduate, Undergraduate

Tasks:

 Student: name, rollNo


 Graduate: thesisTitle, advisorName
 Undergraduate: internshipCompany, semester

Instructions:

 Use virtual display() in base and override in derived.


 Create both derived objects, call display functions using base class pointers
------------------------------------------------------------------------------------------------------------------------------------------

16. Scenario: E-commerce


 Product → ClothingProduct, ElectronicProduct, GroceryProduct

Tasks:

 Use function overloading + overriding


 Each subclass has its own attributes and discount calculation.
 Use polymorphism to display details of multiple types of products using a base pointer
array.

------------------------------------------------------------------------------------------------------------------------------------------

17. Scenario: Sports system


 Athlete is base; derived: Swimmer, Runner, Cyclist

Tasks:

 Use abstract class Athlete with pure virtual calculateSpeed()


 Implement different formulas for each athlete type
 Store in array of pointers and calculate average speed of all

------------------------------------------------------------------------------------------------------------------------------------------

18. Scenario: Transport booking


 Base: Vehicle
 Derived: Bus, Train, Plane

Instructions:

 Vehicle: source, destination, virtual calculateFare()


 Derived: specific fare calculations
 Take user input for type and details, then calculate total fare
 Use dynamic binding to call appropriate functions

------------------------------------------------------------------------------------------------------------------------------------------

19. You are designing a system for a university to manage all types of people involved. Create the
following hierarchy:

 Abstract Class Person


o Attributes: name, CNIC (private)
o Pure virtual function: void display()
o Protected function: void basicInfo() to show name and CNIC
 Class Employee (inherits from Person)
o Attributes: employeeID, department
o Override display() to show employee data
o Constructor chaining required
 Class Student (inherits from Person)
o Attributes: rollNo, program
o Function: display() overridden, input method required
 Class TeachingAssistant (inherits from both Employee and Student)
o Attribute: hourlyRate
o Function: calculateSalary(int hours)
o Override display() to show all inherited data
o Must resolve any ambiguity using scope resolution or virtual inheritance

Tasks:

1. Use proper constructor chaining across all classes.


2. Use virtual inheritance if ambiguity arises due to diamond problem.
3. Create an array of base class Person*, store different object types (Student, Employee, TA).
4. Use runtime polymorphism to call display() on each.
5. Input data dynamically using new, delete objects after use.

------------------------------------------------------------------------------------------------------------------------------------------

20. Build a system for managing multiple modes of transport.


 Class Transport
o source, destination, and a virtual function calculateFare()
 Class Vehicle (inherits from Transport)
o vehicleID, capacity
o Pure virtual function displayDetails()
o Override calculateFare() in a general way (e.g., based on distance)
 Classes Bus, Train, Airplane inherit from Vehicle (Hierarchical Inheritance)
o Add specific fare logic and override displayDetails()
o Additional attributes like classType, mealIncluded, travelTime
 Class CargoService inherits from Vehicle and also from TaxableEntity (Multiple
Inheritance)
o TaxableEntity: abstract class with calculateTax()
o CargoService: adds cargoWeight, baseCost, overrides both virtual functions
 Class LuxuryBus inherits from Bus (Multilevel)
o Adds TVScreens, massageSeats, overrides displayDetails()
o Calls parent constructors

Tasks:

1. Show constructor chaining in all classes.


2. Use abstract base classes where needed.
3. Create 5 different objects (1 of each derived type) using dynamic memory.
4. Store them in a base class pointer array (Vehicle*) and call both calculateFare() and
displayDetails() polymorphically.
5. Demonstrate use of virtual base classes if ambiguity occurs.
6. Properly clean up memory using destructors.

------------------------------------------------------------------------------------------------------------------------------------------

21. Design a banking system with the following class structure:


 Abstract Class Account
o Data members: accountNumber, balance
o Pure virtual function void calculateInterest()
o Virtual function void displayAccount()
 Class SavingsAccount and CurrentAccount inherit from Account
o Add members like interestRate, minimumBalance
o Override calculateInterest() and displayAccount()
o Use different interest formulas
o Use proper constructors and virtual destructor
Tasks:

1. Create an array of base class pointers (Account*) and store both types.
2. Take input for each, call calculateInterest() polymorphically.
3. Add a withdraw(double amount) method in base class. Override in derived classes with
conditions.
4. Demonstrate the use of delete with virtual destructors

------------------------------------------------------------------------------------------------------------------------------------------

22. Scenario:
A university portal handles both administrative and academic data.

 Class User (abstract):


o Attributes: username, loginTime
o Pure virtual: void accessPortal()
o Virtual: void displayInfo()
 Class Faculty and Admin inherit from User
o Faculty: subject, timetable
o Admin: department, permissions
 Class TeachingAdmin inherits from both Faculty and Admin
o Ambiguity must be resolved via virtual inheritance
o Implements accessPortal() and displayInfo() fully

Tasks:

1. Create User* array to hold all types and call virtual functions polymorphically.
2. Input data for each object dynamically.
3. Use proper destructor chaining (make base class destructors virtual).
4. Demonstrate how virtual inheritance helps avoid ambiguity of User.

------------------------------------------------------------------------------------------------------------------------------------------

23. Create an intelligent assistant system:


 Base class: AssistantModule
oPure virtual: respondToCommand(string command)
oVirtual destructor
oAdd a method printModuleType()
 Derived classes:
o WeatherModule, MusicModule, ReminderModule
o Each responds differently to commands
o Use internal string arrays to store previous commands dynamically (DMA)

Tasks:

1. Use AssistantModule* to create an array of 5 modules (some repeated).


2. Take commands from user and use dynamic dispatch to trigger the correct module.
3. Add a function that accepts AssistantModule& and uses dynamic dispatch.
4. Properly deallocate all dynamic memory and test virtual destructors.
5. Add and test a copy constructor for each derived class.

------------------------------------------------------------------------------------------------------------------------------------------

24. Task:
Create a function template add() that can accept two parameters of any type and return their
sum. Demonstrate this for:

 Two integers
 Two floats
 Two characters (use ASCII logic)

------------------------------------------------------------------------------------------------------------------------------------------

25. Task:
Create a class template Pair<T1, T2> that holds two values of potentially different types.

 Add constructor
 Add a method void displayPair() to print them
 Create 3 objects:
o Pair<int, int>
o Pair<string, double>
o Pair<char, bool>
Demonstrate its working in main().

------------------------------------------------------------------------------------------------------------------------------------------

26. Task:
Write a function template findMinMax() that takes an array of any numeric type and:

 Returns both minimum and maximum elements (use Pair<T, T> from Q2 if desired)
 Works with int, float, and double

Use template specialization for char[] to return highest and lowest alphabet.

------------------------------------------------------------------------------------------------------------------------------------------

27. Task:
Build a reporting system with the following:

 Abstract Base Class Template:

template <typename T> // code


class Report {
protected: string title;
public:
virtual void generate(T data) = 0;
virtual ~Report() {}
};

 Derived Template Classes:


o StudentReport<int>: accepts student marks
o SalesReport<double>: accepts monthly sales figures

Each derived class:

 Implements generate() with logic specific to the data type


 Prints average, max, min, etc.

Requirements:

1. Use a base class pointer array Report<T>* and store both StudentReport and SalesReport
2. Call generate() polymorphically
3. Demonstrate inheritance + template usage cleanly

------------------------------------------------------------------------------------------------------------------------------------------

28. Task:
Write a program that asks the user to input two integers and divides the first by the second. If the
second number is zero, throw an exception and catch it to display "Division by zero is not
allowed!".

------------------------------------------------------------------------------------------------------------------------------------------

29. Task:
Write a program that takes a user's age and name.

 Throw an int exception if the age is negative


 Throw a string exception if the name is empty

Use multiple catch blocks to handle both exceptions separately.

------------------------------------------------------------------------------------------------------------------------------------------

30. Task:
Create a class NegativeBalanceException to handle banking errors.

 Create a class BankAccount with balance and withdraw functions


 If withdrawal amount > balance, throw NegativeBalanceException
 Catch the exception in main() and display a custom error message

Your custom exception should:

 Be a separate class
 Contain a what() or getMessage() function to describe the issue

------------------------------------------------------------------------------------------------------------------------------------------
31. Task:
Create a class ResourceHandler that:

 Allocates dynamic memory in constructor


 Has a method that may throw exception (e.g., file open, divide by zero, etc.)
 Uses proper destructor to clean up the resource

Test the following in main():

 Throw exception inside the class method


 Make sure destructor is called
 Wrap object creation in try-catch to ensure no memory leak occurs

------------------------------------------------------------------------------------------------------------------------------------------

32. Scenario:
You are tasked with building a University Grading Portal where students from different departments
can log in and check their grades.

Instructions:

1. Create an abstract base class User with:


o username, loginTime
o Pure virtual function void showDashboard()
2. Create derived classes:
o CSStudent and BioStudent
o Each should override showDashboard() to show different grading criteria
3. Throw a LoginException (user-defined) if login time is before 8 AM or after 6 PM.
4. In main(), use an array of base class pointers and polymorphically show dashboards for both
types.

Also implement:

 Proper destructors
 Base class pointer usage
 Exception handling
------------------------------------------------------------------------------------------------------------------------------------------

33. Scenario:
You’re developing an e-commerce platform backend. Each product has a stock level and price.

Instructions:

1. Create a class template Product<T>, where T is price (float/double).


2. Add:
o name, quantity, T price
o Overload + operator to add stock
o purchase(int count) method that throws an OutOfStockException if count >
quantity
3. In main():
o Create 3 different products
o Show how stock is managed
o Catch exceptions

Make sure to:

 Use templates for at least float and double


 Show real inventory control using overloaded operator

------------------------------------------------------------------------------------------------------------------------------------------

34.Scenario:
You're developing a Smart Traffic Light Control System with different modes for Day, Night,
and Emergency.

 The system must use dynamic dispatch to determine how long each light stays ON.
 Based on real-time traffic data (could be float, int, etc.), use a template function or
class.
 If the data received is invalid (e.g., negative traffic count), throw an exception.

Requirements:

 Use base class polymorphism to switch behavior based on mode.


 Use template logic to process traffic data of various types.
 Show exception handling for invalid input.
 There should be a run() function called polymorphically for each mode.

------------------------------------------------------------------------------------------------------------------------------------------

35. Scenario:
You are developing a Hospital Patient Management System that handles in-patient, out-
patient, and emergency cases.

 Each patient has common info: name, age, medical history.


 In-patient requires room info, admission date.
 Out-patient requires appointment time and doctor ID.
 Emergency patients inherit from both and override behavior.

System Requirements:

 Implement using multiple inheritance.


 Use templates for storing history (vector<T> of medical conditions or reports).
 If patient data is incomplete (e.g., no name), throw a custom
InvalidPatientException.
 Call processPatient() using a base class pointer and override in each derived class.

------------------------------------------------------------------------------------------------------------------------------------------

36.
Scenario:
Design a University Attendance Tracker.

 Abstract class Person with pure virtual markAttendance() and displayRecord().


 Derived: Student, Teacher, and Admin.
 Throw DuplicateEntryException if a person marks attendance twice on the same day.
 Store and display attendance logs using base class pointers.
------------------------------------------------------------------------------------------------------------------------------------------

37. Design a system for managing software license keys. A base class License should store
licenseID, type, and expiryDate.
Derive TrialLicense and PremiumLicense.
Add a function validate() that throws a LicenseExpiredException if the current date is past
expiry. Demonstrate exception catching in main() using base class pointers.

------------------------------------------------------------------------------------------------------------------------------------------

38.
Build a templated class Vector3D<T> to represent a 3D point. Derive PhysicsVector<T> that
adds magnitude and direction. Overload +, - operators. Create an array of base pointers to
manipulate both Vector3D and PhysicsVector objects.

------------------------------------------------------------------------------------------------------------------------------------------

39.
Create a function template safeDivide(T a, T b) that divides two numbers and throws a
DivisionByZeroException if b is zero. Use it to divide values of various types (int, float, double) and
demonstrate catching the exception in main().

------------------------------------------------------------------------------------------------------------------------------------------

40.
Create a class template Account<T> to hold account numbers and balance. Derive
SavingsAccount<T> and CurrentAccount<T>. Add a withdraw(T amount) method that throws
InsufficientBalanceException. In main(), simulate withdrawal attempts for both account types.
------------------------------------------------------------------------------------------------------------------------------------------

41.
Create classes Person and ContactInfo, both with a method displayInfo(). Derive Customer
from both. Resolve ambiguity using virtual inheritance. Call displayInfo() polymorphically
using a base pointer and show full customer info.

------------------------------------------------------------------------------------------------------------------------------------------

42.
Create a hierarchy: Device → SmartDevice → SmartWatch. Use templates in SmartDevice to
handle battery type. Override a function diagnose() at each level. Call diagnose() using a
Device* pointer for a SmartWatch object.

------------------------------------------------------------------------------------------------------------------------------------------

43. Scenario:
You’re designing a type-generic Online Wallet System for different currencies.

 Create a class template Wallet<T> that stores balance of type T.


 Derive CryptoWallet<T> and BankWallet<T>, each with their own withdraw(T)
function.
 If a withdrawal exceeds balance, throw OverdraftException.
 Use base pointers and show polymorphic withdrawal and balance display for different
wallet types in main().

------------------------------------------------------------------------------------------------------------------------------------------
44. Scenario:
Build a Smart Home Controller System.

 Create base classes Sensor and Appliance (both have a virtual function status()).
 Create a derived class SmartAirConditioner inheriting from both, resolving function
ambiguity.
 If sensor reports an invalid reading (e.g., negative temperature), throw
SensorFailureException.
 Use polymorphism to show the status() of multiple smart devices.

------------------------------------------------------------------------------------------------------------------------------------------

45. Scenario:
You’re tasked with creating a Student Feedback System.

 Base class: Feedback<T> where T is the type of feedback rating (int, float, etc.).
 Derived classes: CourseFeedback, FacultyFeedback, EventFeedback.
 All classes should override displayFeedback() and store both numeric and written
feedback.
 Use a template function to calculate average feedback scores and print per category.

------------------------------------------------------------------------------------------------------------------------------------------

46.
Scenario:
Create a Parcel Delivery Simulator.

 Base class: Parcel with a virtual calculateDeliveryTime() function.


 Derived: LocalParcel, InternationalParcel.
 Use a function template to calculate cost based on weight and distance of different types
(float, int).
 Throw InvalidWeightException if weight <= 0.
 In main(), simulate delivery for 3 parcel types and handle all exceptions.

------------------------------------------------------------------------------------------------------------------------------------------

47.
You are required to develop a basic version of a Library Membership and Book Management System
using C++. The system will manage books, members, and their borrowing activity. The goal is to
demonstrate your understanding of object-oriented principles including inheritance, polymorphism,
templates, and exception handling.

Requirements:

1. Book Hierarchy (Inheritance + Templates)

 Create a class template Book<T> where T is the type of the book ID (can be int, string, etc.).
 The class should contain:
o T bookID, string title, string author, bool isIssued
o Member functions: issueBook(), returnBook(), displayDetails()
 Derive two classes:
o TextBook<T> – includes an extra attribute string subject
o Magazine<T> – includes an extra attribute string issueMonth
 Use virtual functions to override displayDetails() in derived classes.

2. Member Classes (Inheritance + Exception Handling)

 Create a base class Member with attributes: memberID, name, email


 Derive:
o Student – includes program and semester
o Faculty – includes designation and department
 Add a borrowBook(Book<T> b) method. If a member tries to borrow more than 3 books,
throw a custom exception BorrowLimitExceeded.

3. Polymorphism and Templates

 Use a base class pointer to manage and display details for books and members polymorphically.
 Create a function template calculateFine(T daysLate) that returns fine based on days
late.
 Use this function to calculate fines for different member types in returnBook().
4. Exception Handling

Handle the following cases using user-defined exceptions:

 Borrowing a book that is already issued


 Returning a book not previously borrowed
 Borrowing limit exceeded

In main():

 Create at least 2 books and 2 members (one student and one faculty)
 Demonstrate issuing, returning, and displaying book/member information using base class
pointers
 Demonstrate template usage and exception handling

------------------------------------------------------------------------------------------------------------------------------------------

48. You are building a Result Processing System.

 Abstract base class Result with pure virtual calculateGrade() and exportToFile().
 Derived: InternalResult, FinalResult.
 Grades are calculated differently in each.
 If marks are missing or invalid (negative), throw InvalidMarkException.
 Store multiple Result* pointers and loop through them to display grades and simulate
export.

------------------------------------------------------------------------------------------------------------------------------------------

49. Scenario:
A tech company is developing a system to handle employee performance across various
departments.
 Each department evaluates performance differently, and some use monthly metrics, while
others rely on quarterly reviews.
 If an evaluation score is negative or missing, the system must throw an exception.
 The company wants to use a unified interface to trigger performance evaluations for all
departments.

Task:
Design a class structure that models this system. Use inheritance to represent different
departments and polymorphism to handle evaluation calls dynamically. Implement exception
handling for invalid evaluation scores. Demonstrate your system by evaluating at least 3
employees from different departments.

------------------------------------------------------------------------------------------------------------------------------------------

50. Scenario:
You're hired to build a generic system for managing product inventories in a warehouse.

 Products can belong to categories like electronics, perishables, or textiles.


 Each product has common attributes (ID, name, quantity) and also category-specific
behavior.
 You must use generic programming to handle product types of different data formats
(e.g., weight in float, count in int).
 The system should allow extending new product types in the future and should provide
detailed product summaries using a single unified method.

Task:
Implement a flexible class design using templates and multiple inheritance where required.
Ensure the system handles category-specific logic correctly and demonstrates extensibility. Use
virtual functions where appropriate to allow dynamic summary generation across product types.

------------------------------------------------------------------------------------------------------------------------------------------

You might also like