PDA

View Full Version : "cout"ing an object


SolarBear
04-15-2004, 11:51 PM
Say I have an object of some class with a few members and methods. Apart from the obvious DisplayObject() method, is there any way of using a simple cout <<MyObject ?

In Python, I'd define a __str__() method inside my class, but I have no clue how to achieve that in C++.

php_brian
04-16-2004, 12:10 AM
The only way I can think of to display information about the object is to have method that is coded for that. There isn't a simple way to perform that operation. Maybe you could doing something by overloading the << operator, but I don't know enough about C++ to do something like that.

little birdy
04-16-2004, 08:10 AM
the only way i've ever done that sort of thing is by overloading the << operator.

friend ostream& operator<<(const ostream& s, const MyObject& obj) {
s << obj.attribute << endl;
/* more s << ___; statements if there are more attributes to print */

return s;
}

sans-hubris
04-16-2004, 10:48 AM
Originally posted by little birdy
the only way i've ever done that sort of thing is by overloading the << operator.

friend ostream& operator<<(const ostream& s, const MyObject& obj) {
s << obj.attribute << endl;
/* more s << ___; statements if there are more attributes to print */

return s;
}
That's exactly right. Operator overloading (http://cplusplus.com/doc/tutorial/tut4-2.html), :smilwink: :thumbup:

sicarius
04-16-2004, 11:39 AM
I know it isn't as C++ or even as efficient (memory wise), but I prefer to just declare a ToString() member function. Why?

More or less personal preference.

gold_dragon
04-16-2004, 12:12 PM
Originally posted by sicarius
I know it isn't as C++ or even as efficient (memory wise), but I prefer to just declare a ToString() member function. Why?

More or less personal preference. Nothing wrong with that, I would assume that having both overloading the << and having member function would be useful to a programmer.

In Java, I don't think there is any other way besides making a member function so I would assume it would be easier to port between the two languages that way.

sicarius
04-16-2004, 02:30 PM
It isn't really that either. Sometimes you just want a string to mess with instead of dumping the text to an output stream.

SolarBear
04-16-2004, 11:07 PM
Thanks a lot guys.

*will need to look at operator overloading*