Library Inheritance
Build a basic library system. Start with a base class LibraryItem that includes common attributes like title, author, and itemID. Then, create two derived classes, Book and DVD.
- The
Bookclass should have an additional attributepageCountand a methoddisplay_info()that prints all details of the book. - The
DVDclass should have an additional attributeduration(in minutes) and a methoddisplay_info()that prints all details of the DVD.
Demonstrate the creation of a Book and a DVD object and display their information.
Answer
#include <iostream>
class LibraryItem {
public:
std::string title;
std::string author;
int itemID;
LibraryItem(std::string t, std::string a, int id)
: title(t), author(a), itemID(id) {}
};
class Book : public LibraryItem {
public:
int pageCount;
Book(std::string t, std::string a, int id, int pages)
: LibraryItem(t, a, id), pageCount(pages) {}
void display_info() {
std::cout << "Book Info:\n";
std::cout << "Title: " << title << "\n";
std::cout << "Author: " << author << "\n";
std::cout << "Item ID: " << itemID << "\n";
std::cout << "Page Count: " << pageCount << "\n";
}
};
class DVD : public LibraryItem {
public:
int duration;
DVD(std::string t, std::string a, int id, int dur)
: LibraryItem(t, a, id), duration(dur) {}
void display_info() {
std::cout << "DVD Info:\n";
std::cout << "Title: " << title << "\n";
std::cout << "Author: " << author << "\n";
std::cout << "Item ID: " << itemID << "\n";
std::cout << "Duration: " << duration << " minutes\n";
}
};
int main() {
Book myBook("1984", "George Orwell", 123, 328);
DVD myDVD("Inception", "Christopher Nolan", 456, 148);
myBook.display_info();
myDVD.display_info();
return 0;
}