0

This code is a Fraction that adds/subtracts multiple inputs of fractions. Here is my header file:

#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
using namespace std;


class Fraction{

    public: 
    Fraction(int , int );
    int fraction(int,int);
    void reduce_fraction(int *,  int *);
    Fraction& operator+(const Fraction&);
    Fraction& operator-(const Fraction&);
    friend ostream& operator<<(ostream &os, const  Fraction& n);
    friend istream& operator>>(istream &is, const Fraction& n);


};

#endif

and here is the overloading the operator code which results in an error of invalid initialization of non-const reference of type'Fractions&' from an rvalue of type 'Frations' for all three overloads

Fraction& Fraction::operator+(const Fraction& n) {
    int denom = *denomp * n.denom;
    int numera = (*nump * n.numera) + (n.denom * n.nump);
    return Fraction(numera,denom);
}

Fraction& Fraction::operator-(const Fraction& n) {
    int denom = *denomp * n.denom;
    int numera = (*nump * n.numera) - (n.denom* n.nump);
    return Fraction(numera, denom);
}
Fraction& Fraction::operator=(const Fraction& n){
    if(this==&n) return *this;
    return n;
}
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
  • 2
    `operator +` should not return a reference, same for `operator -`. Both should return a by-value *copy*. I suggest reading [**this question**](http://stackoverflow.com/questions/4421706/operator-overloading), in particular the sections on arithmetic overloading. – WhozCraig Oct 26 '14 at 00:30
  • `operator+` should not return a reference because it makes little sense semantically. But technically, the problem is that non-const (lvalue) references (your return type) cannot bind to temporaries (rvalues, what you return.) Both problems are solved by returning by value. – juanchopanza Oct 26 '14 at 00:30
  • I'm fairly new to c++, thanks for explaining that I should not be returning a reference, but how do you return by value and can I return two variables? – truedisciple Oct 26 '14 at 00:43

1 Answers1

0

Your assignment operator returns a Fraction &

return n;

This is a const Fraction &

This is the error the compiler is complaining about. You're trying to return a reference to a const object, when the function returns a reference to a non-const object.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • so would i fix it my removing the constant and so it'll pass a value – truedisciple Oct 26 '14 at 00:54
  • @truedisciple You might fix a compiler error, but your assignment operator is badly broken. Think of what assignment is supposed to do to an object. – juanchopanza Oct 26 '14 at 01:02
  • In other words: an assignment operator is always expected to return *this. Always. You can do some funny business, if you detect that the object is being assigned is the same object (which can rarely be done in a portable manner), but in all cases, you are expected to return *this. – Sam Varshavchik Oct 26 '14 at 01:08