PDA

View Full Version : operator<<



mickey
9th June 2008, 23:31
Hello,
could anyone at first sight tell me about why this below doens't work with keyword "const" (that I guess the right way) and it works without it? thanks


friend std::ostream& operator<<(std::ostream& os, const Apple& a) { // <- "const"
return os << "kind = " << a.getKind().c_str() << "\t"
<< "weight = " << a.getWeight() << "\t" << "status = " << a.getStatus().c_str() << endl;
}

jacek
10th June 2008, 00:25
why this below doens't work with keyword "const" (that I guess the right way) and it works without it?
Most likely because at least one of the Apple::getXxx() methods is not const.

http://www.parashift.com/c++-faq-lite/const-correctness.html

mickey
10th June 2008, 00:39
It was that! Furthermore always at first sight: I have to do this:


class Fruit {
virtual friend ostream& operator<<(ostream& os, const Fruit& f) { }
};
class Apple : public Fruit {
friend ostream& operator<<(ostream& os, const Apple& a) { }
};
//main.cpp
Fruit* f = new Apple;
cout << *f;

This above doens't work.......what I like obtain is make virtual the operato<< (I guess you can guess it from the piece of code).....

thanks....

jacek
10th June 2008, 00:50
You can't define ostream & ostream::operator<< ( const Fruit & a ) in Fruit class, because it belongs to ostream class, and you can't change the definition of ostream class, so the only place you can put that operator<< is outside any class:
class Fruit
{
...
virtual void storeOrWhatever( ostream & os ) const = 0;
};

class Apple : public Fruit
{
...
void storeOrWhatever( ostream & os ) const { ... }
};

ostream& operator<<( ostream& os, const Fruit & a )
{
a.storeOrWhatever( os );
return os;
}This way you can easily call the base class implementation and you don't need any friends.