Coming from a more Java background I am wondering how to return a new object by reference. I want the Fraction
class to be immutable, so that every operation returns a new object with the result of the operation.
This would be my code in Java:
class Fraction {
int numerator;
int denominator;
// Constructor
Fraction multiply(Fraction other) {
return new Fraction(other.numerator * this.numerator,
other.denominator * this.denominator);
}
}
But if I would do that in C++ I would create a memory leak because I am not capable of cleaning up the initialized Fraction
object, because I have only a reference to the object. So, how do I deal with this in C++?
class Fraction {
private:
int32_t numerator;
int32_t denominator;
public:
Fraction(int32_t numerator, int32_t denominator) {
this->numerator = numerator;
this->denominator = denominator;
}
Fraction& operator*(Fraction& other) {
auto numerator = other.numerator * this->numerator;
auto denominator = other.denominator * this.denominator;
return *(new Fraction(numerator, denominator))
}
};