Library Book Inheritance

Library Book Inheritance Access

Create a struct Book with the following public members: std::string title, std::string author, std::string isbn, int stock.

Create a struct LibraryBook that inherits privately from Book and adds getter and setter functions for all members, as well as validations to ensure invariants:

Demonstrate the usage by creating an object of LibraryBook and setting and getting the details, ensuring the validations work correctly.

Hint

Use private inheritance to make all members of Book private in LibraryBook.

Answer

#include <iostream>
#include <string>

struct Book {
    std::string title;
    std::string author;
    std::string isbn;
    int stock;
};

struct LibraryBook : private Book {
public:
    // Getter functions
    std::string get_title() const { return title; }
    std::string get_author() const { return author; }
    std::string get_isbn() const { return isbn; }
    int get_stock() const { return stock; }

    // Setter functions with validations
    void set_title(const std::string& t) { title = t; }
    void set_author(const std::string& a) { author = a; }
    void set_isbn(const std::string& i) {
        if (i.length() == 13) {
            isbn = i;
        } else {
            std::cerr << "Invalid ISBN: Must be 13 characters long.\n";
        }
    }
    void set_stock(int s) {
        if (s >= 0) {
            stock = s;
        } else {
            std::cerr << "Invalid stock count: Cannot be negative.\n";
        }
    }

    void display_info() const {
        std::cout << "Title: " << title << "\n";
        std::cout << "Author: " << author << "\n";
        std::cout << "ISBN: " << isbn << "\n";
        std::cout << "Stock: " << stock << "\n";
    }
};

int main() {
    LibraryBook myBook;
  
    myBook.set_title("The C++ Programming Language");
    myBook.set_author("Bjarne Stroustrup");
    myBook.set_isbn("1234567890123");  // Valid ISBN
    myBook.set_stock(10);  // Valid stock count

    // Try setting an invalid ISBN and stock count
    myBook.set_isbn("12345");  // Invalid ISBN
    myBook.set_stock(-5);  // Invalid stock count

    myBook.display_info();  // Display the book details
  
    return 0;
}
Questions