Book arrows

Book Arrows

This program has some ambiguitiy in the setter functions and suboptimal readability in the main function. Improve the ambiguity and readability of this code by adding arrow operators.

#include <iostream>
#include <string>

struct Book {
private:
    std::string title;
    std::string author;
public:
    // setter and getter functions for author
    void set_title(const std::string& title) {
        title = title;
    }
    std::string get_title() const {
        return title;
    }

    // setter and getter functions for author
    void set_author(const std::string& author) {
        author = author;
    }
    std::string get_author() const {
        return author;
    }

    // Method to print book details
    void printDetails() {
        std::cout << "Title: " << title << ", Author: " << author << std::endl;
    }
};

int main() {
    // Creating a Book object dynamically
    Book* myBook = new Book();

    (*myBook).set_title("The Great Gatsby");
    (*myBook).set_author("F. Scott Fitzgerald");

    (*myBook).printDetails();

    // Deleting the Book object to free memory
    delete myBook;

    return 0;
}

Hint

(*myBook). can be changed to myBook->.

Use this-> inside get_author and get_title.

Answer

#include <iostream>
#include <string>

struct Book {
private:
    std::string title;
    std::string author;

public:
    // setter and getter functions for author
    void set_title(const std::string& title) {
        this->title = title;
    }
    std::string get_title() const {
        return title;
    }

    // setter and getter functions for author
    void set_author(const std::string& author) {
        this->author = author;
    }
    std::string get_author() const {
        return author;
    }

    // Method to print book details
    void printDetails() {
        std::cout << "Title: " << title << ", Author: " << author << std::endl;
    }
};

int main() {
    // Creating a Book object dynamically
    Book* myBook = new Book();

    // Setting the title and author with arrow operators
    myBook->set_title("The Great Gatsby");
    myBook->set_author("F. Scott Fitzgerald");

    myBook->printDetails();

    // Deleting the Book object to free memory
    delete myBook;

    return 0;
}

It's worth noting that the changes to set_author and set_title could be resolved by renaming the parameter.

Questions