istream / osteam objects

In my book, I've come across this:

1
2
3
4
5
6
7
8
9
10
11
istream &read(istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}
ostream &print(ostream &os, const Sales_data &item)
{
    // ...
}


And a call to read:

1
2
3
4
Sales_data::Sales_data(std::istream& is)
{
    read(is, *this); // read will read a transaction from is into this object
}


It hasn't explained why we're using ostream objects nor what they or. Neither before in the book has it, this is my first time seeing this syntax. I'm wondering why exactly we made an istream object. Why not just use std::cin on line 4? And in the call couldn't we just do read(std::cin, *this) instead?
Last edited on
C++ Primer(Chpater 7: Classes)
From main(), when you construct a Sales_data object, you may not want to supply the data yourself, you probably need the user(program user this time) to do this, so you call a Sales_data object like this:

Sales_data obj(std::istream &);

In your Sales_data Class that uses an std::istream & to populate its data member, it "binds" the std::cin to "is" which has been defined in read() as std::istream object, so instead of using std::cin again, is represents it.
Moreover, since read() isn't a member function of ANY of the Classes but rather a friend function, it takes ANY input stream(std::ifstream, std::istringstream) as a parameter. So, read() takes two arguments, any member of std::istream family and a pointer to the object in execution.
Remember that, std::cin is a member of the std::istream family.
Last edited on
Thanks for that. I've only used cin for input so I understand now.

So, just to be sure, we used std::istream rather than std::cin directly so we could allow for other types of input if we wanted later?
Last edited on
Topic archived. No new replies allowed.