1

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 ?

Ediolot
  • 501
  • 2
  • 6
  • 19
  • 1
    "But with polymorphism I have to return a pointer..." No; you don't. Here you'd better have to return a number_t by value also. (a+b) should be a number_t. – Loreto Mar 25 '16 at 18:54
  • It is ok to just do `number_t real_t::operator+(...) { ... return real_t(...); }` ? I thought that only worked with pointers, thanks. – Ediolot Mar 25 '16 at 19:54
  • No, it's not ok. You will [slice](http://stackoverflow.com/q/274626/3425536) the object. Why not declare the return type to be `real_t` if you're returning a `real_t`? Users can still handle it as a `number_t` if they want to. – Emil Laine Mar 25 '16 at 20:11
  • The return type will depend on the operands, if I'm adding `real_t` with `complex_t` I will return a `complex_t` but if I'm adding `real_t` with `integer_t` I will return a `real_t`. I will update the question. – Ediolot Mar 25 '16 at 21:14

1 Answers1

0

Return a smart pointer:

unique_ptr<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 */
    return make_unique<real_t>(...); 
}

Now the intermediate value will be freed automatically.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157