-4

I understand the basics of the error message; it is alerting me that this code may not return anything at all. However, I do not understand why. My code is perfect, is it not?

rational operator / (const rational &lhs, const rational &rhs)
{
if(rhs.numerator() != 0)
{
    int numerator = lhs.numerator() * rhs.denominator();
    int denominator = lhs.denominator() * rhs.numerator();
    rational quotient(numerator, denominator);
    return quotient;
}
else cout << "error" << endl;
}   //this is where error is occurring 
Matt C.
  • 2,330
  • 3
  • 22
  • 26

2 Answers2

1

Correction made with inscribed comments.

rational operator / (const rational &lhs, const rational &rhs)
{
  if(rhs.denominator() != 0) {
    int numerator = lhs.numerator() * rhs.denominator() + 
                    rhs.numerator() * lhs.denominator();
    int denominator = lhs.denominator() * rhs.denominator();
    rational quotient(numerator, denominator);
    return quotient;
  }
  else {
   // what should be returned?
   // let's return lhs, as caller is expecting something, lhs is better than nothing
   // ideally should raise exception, and program shopuld not continue further
   cout << "error" << endl; 
   return lhs; 
  }
}
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
0

So its pretty simple right, your function needs to return a type rational. In the case that this fails:

if(rhs.numerator() != 0) 

then you will not return anything of that type. Hence the warning.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • So I can't return any kind of error message? What if there is no type rational that suits the situation? – Matt C. Sep 18 '14 at 03:24
  • @MattC. Then you should consider throwing an exception instead. – Fantastic Mr Fox Sep 18 '14 at 03:25
  • 2
    @MattC.: You defined your function to return a `rational`, so it has to return a `rational` -- or throw an exception. Or you can change the return type so it can always return a sensible value. – Keith Thompson Sep 18 '14 at 03:25