views:

420

answers:

1

I'm creating my first class, mainly guided by Overland's C++ Without Fear. I've made the overloaded friend ostream operator<<, which works fine. I've also overloaded the * operator, and that works fine. What doesn't work is when I try to output the result of the * operator directly:

BCD bcd(10);  //bcd is initialised to 10
BCD bcd2(15); //bcd2 is initialised to 15
cout << bcd;  //prints 10
bcd2 = bcd2 * 2; //multiplies bcd2 by 2
cout << bcd2; //prints 30

cout << bcd * 2 //SHOULD print 20, but compiler says
//main.cpp:49: error: no match for 'operator<<' in 'std::cout << BCD::operator*(int)(2)'

For info, here are my prototypes:

BCD operator*(int z);
friend ostream &operator<<(ostream &os, BCD &bcd);

As far as I can tell, operator* returns a BCD, so operator<< should be able to print it. Help please!

+11  A: 

What's happening is that bcd * 2 is generating a temporary BCD, which cannot bind to a BCD &. Try replacing the << operator with one of these:

friend ostream &operator<<(ostream &os, const BCD &bcd);

or

friend ostream &operator<<(ostream &os, BCD bcd);

or even

friend ostream &operator<<(ostream &os, const BCD bcd);

The first one works, since binding a temporary variable to a constant reference is explicity allowed, unlike binding to a non-const reference. The other ones work by making a copy of the temporary variable.

Edit: As noted in the comments - prefer the const & version in most cases, since modifying an object in a streaming operator will be surprising to anyone using your class. Getting this to compile may require adding const declarations to your classes member function where appropriate.

Eclipse
I'd prefer the const variant, since -- obviously -- a << should never modify the parameter.
David Schmitt
+1 and I second David Schmitt's suggestion.
e.James
Good point - it's always best to stick with what is expected from an operator and modifying an object in operator<< would be a suprise indeed.
Eclipse
Josh - you are a god among men! Before your edit about the const declarations I was having problems - but that fixed it! Many many thanks.
Skilldrick