Solved Practical Part 4
OOP
Question 6:
Design a simple class hierarchy for a library management system using object-oriented
principles.
Your design should include at least:
● A base class LibraryItem with appropriate attributes and methods.
● Two derived classes: Book and Magazine.
● Demonstrate the use of constructors, destructors, and function overloading.
● Show how inheritance and polymorphism are applied in your design.
Solution:
Question 1: Library Management System Class Hierarchy
C++ Solution:
cpp
CopyEdit
#include <iostream>
#include <string>
using namespace std;
// Base class
class LibraryItem {
protected:
string title;
int id;
public:
LibraryItem(string t, int i) : title(t), id(i) {
cout << "LibraryItem constructor called for: " << title <<
endl;
}
virtual void display() {
cout << "Title: " << title << ", ID: " << id << endl;
}
virtual ~LibraryItem() {
cout << "LibraryItem destructor called for: " << title <<
endl;
}
};
// Derived class - Book
class Book : public LibraryItem {
string author;
public:
Book(string t, int i, string a) : LibraryItem(t, i), author(a) {}
void display() override {
cout << "[Book] Title: " << title << ", Author: " << author <<
", ID: " << id << endl;
}
};
// Derived class - Magazine
class Magazine : public LibraryItem {
int issueNumber;
public:
Magazine(string t, int i, int issue) : LibraryItem(t, i),
issueNumber(issue) {}
void display() override {
cout << "[Magazine] Title: " << title << ", Issue: " <<
issueNumber << ", ID: " << id << endl;
}
};
// Function overloading
void printItemDetails(LibraryItem &item) {
[Link]();
}
void printItemDetails(LibraryItem *item) {
item->display();
}
// Main
int main() {
Book b1("The Great Gatsby", 101, "F. Scott Fitzgerald");
Magazine m1("Time", 202, 48);
printItemDetails(b1);
printItemDetails(&m1);
return 0;
}
Concepts Used:
● Inheritance: Book and Magazine inherit from LibraryItem.
● Polymorphism: display() is a virtual function, demonstrating runtime polymorphism.
● Constructors & Destructors: Each class uses constructors and destructors with output.
● Function Overloading: printItemDetails() is overloaded by type of argument.