Printing objects in C++
Archive - Originally posted on "The Horse's Mouth" - 2011-08-13 09:54:09 - Graham Ellis
c = a + b
than
c = a.addition(b)
ans it's also much easier for the maintainance programmer later too - a short and sweet "+" is pretty obvious.
In C++ (which I have been teaching for the last couple of days), you can define an operator within a class simply be defining a method with an appropriate name - a predefined name, in fact, such as operator+. There's an example of that from a course I ran earlier this year - [here].
It gets a little trickier when you want to define how an object is to be output when you pass it to an output stream. You've probably seen code like:
cout << varname << "kgs" << endl
and had it work well for you. And if varname is the name of a standard type such as an integer or a float, it works seemlessly and without the need for much thought. But what if varname is one of your own objects?
Your initial reaction may well be to overload the << operator (actually the left shift operator), but unfortuanatley the object you want to run it on appears to the right of the <<, and so that overriding doesn't work out. What you need to do instead is to provide a method that will work on cout. Here's how ...

Code:
ostream &operator<<(ostream &os, Person &p) {
p.print(&os);
return os;
}
You an then simply implement the print method in your class:
void Person::print(ostream *os) {
*os << "A Person " << weight << " " << height << endl;
}
Demonstration source code for those methods include in a class [here]. The header file (including the function template needed) is [here]. And the new logic is called from a sample test program [here].
Illustrations - lunchtime at Well House Manor on the C++ course that was running there yesterday. We have a selection of lunches during the week, tailored to suit the delegates on each particular week. Yesterday was a "healthy option" lunch - very often that's much more popular that a traditional heavy meal which can take up a lot of valuable learning time, and may leave some of us a little too sleepy and mellow for some of the more challenging subjects.