-2

How can I create be object array of type Book in this program. Tried to create the object but couldnt do it.Its driving me nuts. hence I need a litle help.

    #include<iostream>
#include <algorithm>
using namespace std;

 class BOOK{
    private:
        char bookname[20];
        float bookprice;
    public:
        void getBookDetails()
        {
        cout<<"Enter the Book Name:";
         cin>>bookname;
         cout<<"Enter the Book Price:";
         cin>>bookprice;
          }
          void displayDetails()
          {
            cout<<"Book Name:"<<bookname<<endl;
            cout<<"Book Price:"<<bookprice<<endl;
          }
 };
 bool comparator(string a, string b)
 {
    return a<b;
 }
int main()
{
    int Book=5;
    string sortBook[]={"sandwich","apple","banana","zombie","pear"};
    
    std::sort(sortBook,sortBook+Book,comparator);
       for(int i=0;i<Book;i++)
    {
        cout<<sortBook[i]<<" ";
    }
}
     

}

  • 1
    You could not do it? What happens? Does the program compile? Does it run? If it runs, what happens? What did you expect to happen. Read this; [ask] – Jabberwocky Jun 14 '21 at 13:12
  • 1
    What I miss in your program is any variable of type `BOOK`. E.g. a `BOOK books[5];` in your `main()` function would make an array of 5 books. – Scheff's Cat Jun 14 '21 at 13:14
  • 1
    What does "couldnt do it" mean? – Sam Varshavchik Jun 14 '21 at 13:15
  • 1
    And you are missing the variable `n`. It's used but nowhere defined. – Lukas-T Jun 14 '21 at 13:16
  • 3
    Please read the comments regarding your [last question](https://stackoverflow.com/questions/67969561/named-return-values-are-no-longer-supported). They provide a lot of the information you need. – G.M. Jun 14 '21 at 13:17
  • You have copied code from a wrong answer. Delete all of this, then read your instructions carefully *and follow them*. If you don't understand something, like how to declare an array, or how to define a function called "sortBook", you need to study more, not ask strangers on the internet. – molbdnilo Jun 14 '21 at 14:27

1 Answers1

1

An object array of books would look like this:

int size = 5;
BOOK bookArray[size];

Major Problems

  • You are not using constructors
  • You are unnecessarily using char arrays
  • The string array 'sortBooks' should be a BOOK array (I assume?)
  • You declared a string array without including the string header file (probably the reason your code won't compile)

In my honest opinion, it seems that you are trying to solve a complex task without first mastering the basics of the language. I would highly recommend watching/reading a complete C++ tutorial, such as The Cherno's C++ Guide or NeuralNine's C++ Guide. Reading TutorialPoint's guides on C++ and The C++ Standard Library would also be helpful. Finally, if I had to recommend something more, I would recommend Sam's Teach Yourself C++, which helps you understand that language on a deeper level and covers many intricacies of the C++ language that beginners often overlook (note: I would not recommend using this book by itself, as it can be dry and difficult at times).

The reason your code isn't doing what you want is because you are not declaring an array of type BOOK, but of type string. Once you change the array to type book, you will run into two main problems:

  1. Declaring an array of objects requires a default constructor.
  2. Comparing classes requires operator overloading

Here is a good reference for learning about constructors. Essentially, a constructor is a special function that shares the exact same name as the class. When the class is declared, the constructor is automatically called. You should use a constructor to initialize the values instead of using the getBookDetails() function. If you used a constructor, you would just be able to write BOOK newBookObject("name", price)

Concerns

You are trying to sort an array of objects, which is difficult because objects are custom types, so the computer doesn't know how to compare two objects with a < (less than sign). Because of this, you would have to manually define how to compare the two objects (via operator overloading).

What You Need To Do:

Include the '<string>' Header File

Add #include <string> to the top of the file.

Change 'char bookname[20]' to 'string bookname'

I would not recommend using char arrays with classes, as it is difficult for a beginner. I agree with this question in that there's no reason to not using a string here, especially when you've already included the string library for the 'sortBooks' array you have at the bottom.

Add a Default Constructor

A default constructor is necessary to declare an array of objects.

BOOK()
{
    bookname = ""
    bookprice = 0.0
}

Add a Parameterized Constructor

A parameterized constuctor will allow you to declare a BOOK object like this:
BOOK newBook("book name here", price)

An Example:
BOOK newBook("Pride and Prejudice", 50.00)

BOOK(string book_name, double book_price)
{
    bookname = book_name;
    bookprice = book_price;
}

You can have two methods of the same name, as long as they have different parameters; this is called method overloading

Change the 'sortBooks' array to type BOOK

BOOK bookArray[5] { book1(title, price), book2(title, price) book3(title, price) book4(title, price) book5(title, price) }; Replace 'title' and 'price' with the appropriate titles and prices

Overload the '<' Operator

Comparing by Book Name
bool operator < (BOOK& otherBook)
{
    return bookname < otherBook.bookname;
}

Comparing by Price
bool operator < (const BOOK& otherBook)
{
    return bookprice < otherBook.bookprice;
}

Just some nitpicks/extra advice:

  • You don't have to name the data members 'bookname' and 'bookprice'. Since it's already in the context of a class, you could just write 'name' and 'price'.
  • As a beginner, you should always use doubles instead of floats, since floats have the possibility of introducing rounding errors.
  • Name classes using PascalCase

Finally, my code

I compiled this code on an Ubuntu Linux Subsystem using G++ (version: 9.3.0)

#include <iostream>
#include <string>     //Include the 'string' header 
#include <algorithm>
using namespace std;

class BOOK
{
    //Private data members
    private:
        string bookname; 
        float bookprice;

    //Public methods
    public:
        BOOK()
        {
            bookname;
            bookprice = 0.0;
        }

        BOOK(string name, double price)
        {
            bookname = name;
            bookprice = price;
        }

        void getBookDetails()
        {
            cout << "Enter the Book Name: ";
            cin >> bookname;
            //Add a 'cout << endl;' here
        

            cout << "Enter the Book Price: ";
            cin >> bookprice;
            //Add a 'cout << endl;' here
        }

        void displayDetails()
        {
            cout << "Book Name: " << bookname << endl;
            cout << "Book Price: " << bookprice << endl;
        }

        bool operator < (BOOK& otherBook)
        {
            return bookname < otherBook.bookname;  //You can access private data members within the same class
        }
};


int main()
{
    int size = 5;
    BOOK bookArray[5];   //an array of 5 'BOOK' objects

    if (bookArray[0] < bookArray[1])        //Both have the same value, "" (the default value)
        cout << "Item 1 is greater" << endl;

    return 0;
}

Ethan Cox
  • 36
  • 2
  • 4
  • Thanks for the guidance and for the codde. But still I am getting empty output. –  Jun 14 '21 at 14:47
  • @UtkarshChauhan The code I provided only instantiates the _BOOK_ array - it does not sort nor print it. Now that you have overloaded the less than operator, you can just write ```sort(bookArray, bookArray + size)``` where size is the size of the array as an integer. Used a [ranged-based for loop](https://www.geeksforgeeks.org/range-based-loop-c/) to print the array easily: ```C++ for (auto book: bookArray) { book.displayDetails(); } ``` – Ethan Cox Jun 14 '21 at 15:03