Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top