Pointers in c++ are passed by value, meaning you can delete the object anywhere you have the pointer (as long as it hasn't already been deleted). Since they essentially just store an address this is fine because when delete is called it knows where and how to free the memory.
In your case you would delete it outside the function otherwise there is no point in returning it. To avoid having to manage the memory yourself you should actually be using an std::unique_ptr
std::unique_ptr<Fraction> Fraction::add(const Fraction* fr) const{
int gcd;
gcd = gcdRecur(num * fr->denom + fr->num * denom,
denom * fr->denom);
std::unique_ptr<Fraction> ptr(new Fraction((num * fr->denom + fr->num * denom) / gcd,
(denom * fr->denom) / gcd));
return ptr;
}
Using this style will save you many headaches and is now considered idiomatic in c++. The parameter fr
could also be passed as a unique_ptr
, to adopt this style of coding you will also want to understand std::shared_ptr
which represents a ptr that does not have unique ownership (more than one can exist).
However the real problem is when you create an object on the heap without saving the pointer with the address of the object. Then that object is lost and cannot be freed.