0

I'm trying to do the following:

class Book {
    std::string m_title;
    std::string m_author;
    int m_noPages;
public:
    Book(const std::istream& is) {
        std::string bookString;
        is >> bookString;

        // ...
    }
};

... After this, I will proceed to separate the is input into m_title, m_author, and m_noPages, but why won't the two lines above inside the constructor work?

1 Answers1

3

When reading from (and writing to) a stream, the stream is modified to track what was read (or written). This makes a const, thus not modifiable, stream next to useless, and it can't be used by >>. Remove the const.

class Book {
    std::string m_title;
    std::string m_author;
    int m_noPages;
public:
    Book(const std::istream& is) {
//       ^^^^^
//       kill meeeeee! 
        std::string bookString;
        is >> bookString;

        // ...
    }
};

Language-wise, the prototype for operator >> should look something like

std::istream& operator>>(std::istream& is, T& obj)

(example prototype looted from What are the basic rules and idioms for operator overloading?). It will accept std::istream &, but not a const std::istream &.

user4581301
  • 33,082
  • 7
  • 33
  • 54