Car class Stream insertion Operator?

Car class- private members names are: name(string), year(int), passenger(int), maker (string). Assume that all kinds of constructors, destructors, mutators, and accessor member functions are defined correctly

For the Car class, define cout's Stream Insertion Operator should cause all private members to be displayed.

I'm drawing a blank for this problem and can't seem to figure out how it should be written.

If anyone can help me out I would really appreciate it.
As a start, can you write the declaration of the operator?
A stream insertion operator is a fancy name for the special function that prints to an iostream.

1
2
3
4
5
6
7
8
9
10
11
12
class Car
{
  ...

  friend ostream& operator << ( ostream& outs, const Car& car );
};

ostream& operator << ( ostream& outs, const Car& car )
{
  outs << car.year << " " << car.maker << " " << car.name << " (" << car.passenger << " passenger)";
  return outs;
}

All output operators (stream insertion operators) will look something like this. The only differences is in how you want to format your output.

Notice that you could have easily used another function name:

1
2
3
4
void print_car( ostream& outs, const Car& car )
{
  outs << car.year << ...;
}

There are only a couple of things that are important to take note of:

(1) The Car argument is a const reference.
(2) The insertion operator returns the stream passed as argument. (It needn't, but in most cases, as in your case, it should.)
(3) You use the argument stream instead of cout.
(4) You don't print a newline at the end of the output. That makes it easy for you to say things later like:

1
2
3
4
Car my_audi_tt;
...

cout << "My " << my_audi_tt << " is awesome!\n";
My 2007 Audi TT (4 passenger) is awesome!

Finally, there is an issue where how you print things matters. The example I gave you prints everything on one line. That's not the only way to do it. Choose how you (or your professor) prefer it.

[edit]
Oh yeah, I almost forgot:

(5) The insertion operator is always a friend function.
[/edit]

Hope this helps.
Last edited on
I got it now.. Thanks!
Topic archived. No new replies allowed.