Using ostream with overloading arithmetic operators for class

1906 views c++

I have class Rational, its fragment:

class Rational {
    int numerator;
    int denominator;
    void saveAsIrreducible();
    gcd(int x, inty);
    Rational(int numerator, int denominator=1);
    Rational operator*(Rational &r);
    friend ostream& operator<<(ostream &output, Rational &r);

And implementation:

Rational::Rational(int numerator, int denominator) {
    this->numerator = numerator;
    this->denominator = denominator;

Rational Rational::operator*(Rational &r) {
    Rational r2 = Rational((this->numerator*r.numerator), (this->denominator*r.denominator));
    return r2;

ostream& operator<<(ostream &output, Rational &r) {
    output << r.numerator;

        output << "|" << r.denominator;

    return output;

void Rational::saveAsIrreducible() {
    int greatestCommonDivisor = gcd(numerator, denominator);
    numerator = numerator/greatestCommonDivisor;
    denominator = denominator/greatestCommonDivisor;
    if(numerator > 0 && denominator < 0) { /* for example for 3|-2, after arithmetic operations */
        numerator = -numerator;
        denominator = -denominator;

int Rational::gcd(int x, int y) {
    while(y!=0) {
        int r = x%y;
        x = y;
        y = r;

    return x;

I have problem with using operator * with cout. For example, it works:

Rational r1(3,5), r2(3,6);
Rational r3 = r1*r2;
cout << r3 << endl;

Output is correct. But when I try do this:

Rational r1(3,5), r2(3,6);
cout << r1*r2 << endl;

I get a lot of errors from the compiler:

Rational.cpp|186|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Rational')|

Rational.cpp|186|error: invalid initialization of non-const reference of type 'Rational&' from an rvalue of type 'Rational'|

How to fix this problem?

answered question

1 Answer


The overloaded operator<< takes Rational& as its argument.

So in the case of the below statements:

Rational r3 = r1*r2;
cout << r3 << endl;

r3 is an lvalue (which contains the result of r1*r2) whose reference is passed to operator<< and it succeeds.

But when you do the below:

cout << r1*r2 << endl;

You are not passing a reference to operator<< because operator* is returning a temporary. So it fails.

posted this

Have an answer?


Please login first before posting an answer.