Author nested in book

Author nested in Book

Create a Book class that contains a nested struct Author with member variables name, nationality, and birth_year. Add member variables to the Book class for title, publication_year, and an Author object. Write methods to set and get the author and book details. Demonstrate the use of the nested Author struct by creating instances of Book and setting/getting author and book details.

Answer

#include <iostream>
#include <string>

class Book {
public:
    // Nested struct Author
    struct Author {
        std::string name;
        std::string nationality;
        int birth_year;

        Author() : name(""), nationality(""), birth_year(0) {}
        Author(const std::string& author_name, const std::string& author_nationality, int author_birth_year)
            : name(author_name), nationality(author_nationality), birth_year(author_birth_year) {}
    };

private:
    std::string title;
    int publication_year;
    Author author;

public:
    // Constructor to initialize book details
    Book(const std::string& book_title, int book_publication_year, const Author& book_author)
        : title(book_title), publication_year(book_publication_year), author(book_author) {}

    // Getter for title
    std::string get_title() const {
        return title;
    }

    // Setter for title
    void set_title(const std::string& book_title) {
        title = book_title;
    }

    // Getter for publication year
    int get_publication_year() const {
        return publication_year;
    }

    // Setter for publication year
    void set_publication_year(int book_publication_year) {
        publication_year = book_publication_year;
    }

    // Getter for author
    Author get_author() const {
        return author;
    }

    // Setter for author
    void set_author(const Author& book_author) {
        author = book_author;
    }

    // Method to print book details
    void print_details() const {
        std::cout << "Title: " << title << std::endl;
        std::cout << "Publication Year: " << publication_year << std::endl;
        std::cout << "Author: " << author.name << std::endl;
        std::cout << "Nationality: " << author.nationality << std::endl;
        std::cout << "Birth Year: " << author.birth_year << std::endl;
    }
};

int main() {
    // Create an Author instance
    Book::Author author1("J.K. Rowling", "British", 1965);

    // Create a Book instance
    Book book1("Harry Potter and the Philosopher's Stone", 1997, author1);

    // Print book details
    std::cout << "Book 1 Details:" << std::endl;
    book1.print_details();
    std::cout << std::endl;

    // Create another Author instance
    Book::Author author2("George Orwell", "British", 1903);

    // Create another Book instance
    Book book2("1984", 1949, author2);

    // Print book details
    std::cout << "Book 2 Details:" << std::endl;
    book2.print_details();

    return 0;
}
Questions