Im learning C++ polymorphism right now and the teacher wanted us to do a calculator using a base class number_t with derived classes: integer_t, real_t, etc..
Without polymorphism I would implant the operator+
very similar to this:
real_t real_t::operator+(const integer_t& number) const
{
/* Sum operations of (real_t + integer_t) */
/* Create a new real with the result of the sum and return it */
return real_t(...);
}
This way, when there is a sum of two numbers it wont be changing the values of the numbers that are involved but returning a new one.
But with polymorphism I have to return a pointer, for example, this is what I will do:
number_t* real_t::operator+(const number_t* number) const
{
/* Sum operations of two numbers which will output a real_t (for example)*/
/* Create a new real with the result of the sum and return it */
/* The return value will be of the type of the biggest set, for example:
integer + real = real
complex + real = complex
*/
return new real_t(...);
}
The problem here is the memory created by new
operator wont be freed. In this operation:
d = (a + b) + c
The memory allocated by the sum (a+b)
wont be never freed.
Is there any better approach for this ?