-

---
Last edited on
need help starting this code

declare the class Book with the attributes within the private section
in the public section of the class list the class methods - accessors that get/return the various attributes of an oject - should be const qualified, mutators that set/change the various attributes of an object and possibly overloaded class ctors to create Book objects
operator overloading: https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm

Test each member function and operator.

this has to be done within main() with some Book objects that you initialize
---
Last edited on
how I can improve the code using constructers

void input() method could become an overloaded ctor straight-off:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

class Book
{
    private:
    std::string m_name;
    std::string m_author;
    double m_price;

    public:
    Book (const std::string& name, const std::string& author, double price)
    : m_name (name), m_author (author), m_price (price){}
    friend std::ostream& operator << (std::ostream& os, const Book& b);

};


Now let's think of what sort of operator overloads might make sense for this class - certainly the stream insertion (<<) and extraction (>>) operators for writing to and reading from streams, so you could overload << as:
1
2
3
4
5
std::ostream& operator << (std::ostream& os, const Book& b)//declared as friend function within class Book
{
    os << b.m_name << " by " << b.m_author << " costs " << "$ " << b.m_price << "\n";
    return os;
}

The link sent in the previous post has a list of C++ operators that can be overloaded - go through the list and see if there are any others that might be suitable for your requirements
Also consider if Book::total_cost() and Book::purchase() need to be member methods, it seems that they could just as well be non-member, non-friend functions without any loss of generality
OP: going through the operator list another one worth overloading might be operator < for sorting books into a catalog or database
Topic archived. No new replies allowed.