I'm not sure if
return *this
is the only way we could return an instance of a class who called a member function? The reason why I asked is because our instructor told us to avoid using pointers if necessary and I'm wondering if this is a case where the only necessary way to do it is by returning the this pointer.
I'm working with a fraction class that holds private data members numerator and denominator. The member function I'm talking about is used to add two fractions for example:
Fraction C = A.plus(B);
plus member function is defined as this:
Fraction& plus( const Fraction frac )
The instructor wants us to do C = A += B , so I guess that's why.
Get a new instructor. It looks as if the declaration of plus() is completely wrong.
That is for likely sensible implementations of a member plus() function. Of course, it should probably be a friend.
I think in this case it is safe to use
return *this
because this refers to the current object so it is guaranteed to exist, so it won't be null.
The reason plus returns reference to itself is so that it can be chained:
Fraction C = A.plus(B).plus(D) // perhaps?
Note that in the above case C will be created by copying the result of addition.
This also assumes that operation plus is meant to modify object (in this case A) and return the reference to this modified object.
Wouldn't plus accept reference instead of making copy of the parameter?
Fraction& plus( const Fraction& frac )
This is similar to how you would implement operator= (an example):
A& operator=(const A& right) {
if(this == &right) return *this; // Handle self-assignment
b = right.b;
return *this;
}
Maybe you would want to not modify object and return new object:
// assuming there's a constructor Fraction(int numerator, int denominator):
Fraction* plus(Fraction const& rhs)
{
return new Fraction(numerator * rhs.denominator
+ rhs.numerator * denominator,
denominator * rhs.denominator);
}
But this of course has to return pointer to new instance which is not a reference as maybe required in your task (?).
Or even better:
Fraction plus(Fraction const& rhs)
{
return Fraction(numerator * rhs.denominator
+ rhs.numerator * denominator,
denominator * rhs.denominator);
}
This will create Fraction in the space of calling function so there's no overhead of copying structure on return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With