I have the following problem: let’s say class Item holds the serial number of a product,
and class Book is an Item which inherits class Item‘s serial number. I have to create and use operator>> for every class. I thought about creating operator>> to Item, and then just call it in the implementation of the istream of the book, but I don’t know how.
The code goes like this:
class Item
{
protected:
int _sn;
public:
Item();
~Item();
...
const istream& operator>>(const istream& in,const Item& x)
{
int temp;
in>>temp;
x._sn=temp;
return in;
}
};
class Book
{
private:
char _book_name[20];
public:
Book();
~Book();
...
const istream& operator>>(const istream& in,const Book& x)
{
char temp[20];
////**here i want to use the operator>> of Item**////
in>>temp;
strcpy(x._book_name,temp);
return in;
}
};
int main()
{
Book book;
in>>book; //here i want to get both _sn and _book_name
}
Is this even possible?
First,
operator>>has to be a free function or afriend, because the left-hand side is not of your class type. Second, the lhs must also be a non-const reference (because the stream changes state on extraction), the same goes for the second parameter (you change state, it needs to be non-const). With that in mind, here’s how the operators should look:Note that I changed your C-style string handling (
char name[20]+strncpy) to astd::string, which is what you should be doing in C++.It can be done even easier if you just implement a
from_streammethod:Thanks to
from_streambeingvirtual, you never need to reimplementoperator>>, it will automatically dispatch to the correct derived class depending with which it was called: