TimKaechele
TimKaechele

Reputation: 530

Returning a new Object by reference

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))
    }
};

Upvotes: 1

Views: 2458

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117856

Don't use new at all, just return by value.

Fraction operator*(Fraction const& other) const
{
    auto numerator = other.numerator * this->numerator;
    auto denominator = other.denominator * this->denominator;

    return Fraction(numerator, denominator);
}

Your latter method will result in a leaked pointer. And you don't need to worry about the returned Fraction being copied thanks to return value optimization

Upvotes: 16

basav
basav

Reputation: 1495

In C++ you have control over where you want to place your object. You can choose stack/heap as per your needs.

I dont't want to confuse you now, but you can lookup use of "placement new" if you want even more conrol over your object's place in memory.

I am not an expert in JAVA but last time I checked, you had to use new to allocate a object in java.

I think this has been explained here pretty well.When to use/not to use new in c++.

When to use "new" and when not to, in C++?

Welcome to the world of C++

Upvotes: 1

Related Questions