Search code examples
c++compiler-errorsistream

Getting invalid initialization of reference of type 'std::istream&' from expression of type 'int'


I am trying to create a class that works with rational numbers and performing operator overloading on them. I am having issue on one part of the program, the input stream.

I am supposed to take input in the format "12/8" for example, and it should store 12 into a variable a and then 8 into a variable b.

Here is my code:

istream& operator>>( istream& In, Rational& Item )
{
    char division_sign;
    int a,b;

    In >> a >> division_sign;
    if (division_sign != '/' || !In.good())
    {
        In.setstate( ios::failbit );
    }
    else
    {
        In >> b;
        if (b != 0 || !In.good())
        {
        return Item.numerator_ = a, Item.denominator_ = b;
        }
    }
}

And here is the error I receive:

In function 'std::istream& operator>>(std::istream&, Rational&)':
131: error: invalid initialization of reference of type 'std::istream&' from expression of type 'int'

Line 131 is the return statement


Solution

  • The compilation error you observe is due to the fact that you try to return a value of another type as you've put into the declaration. You need to return In and not b:

    return In; 
    

    You should therefore return the istream object reference in any possible branch of the function execution path. That is, put only one such return statement to the end of the function.

    Also have a look at this FAQ on operator overloading.