-2

I have a class that contains an array data. I need to write an overloaded operator that returns an object of the class with the addition of two class arrays. For example: Container x({1,2,3}) + y({1,2,3}).

I tried the following and numerically it works, but it doesn't return a new object. I also included the constructors.

Constructors:

Container(){
        length = 0;
        data = nullptr;
    }

    Container(int len){
        length = len;
        data = new double[length];
    }

    Container(std::initializer_list<double> il): Container(il.size())
    {
        std::copy(il.begin(), il.end(), data);
    }

Attempt to overload:

 Container& operator+(const Container& other)
    {
        for (auto i=0; i<other.length; i++){
            data[i] = data[i] + other.data[i];
        }
        return *this;

Could I please get feedback on this?

Tim
  • 415
  • 2
  • 10
  • 3
    why do you expect that operator to return another object? It returns `Container&` and you never create another instance. What you implemented rather looks like `+=`. Maybe you copied from the wrong place – 463035818_is_not_an_ai Nov 30 '20 at 09:52

2 Answers2

4

How do I return another object with operator overloading?

Same way as you would return an object from any function:

Container operator...
//       ^ Return an object; not a reference
{
    Container c ... // create an object
                    // initialise with the desired values
    return c;
}
eerorika
  • 232,697
  • 12
  • 197
  • 326
3

What you implemented modifies this and then returns a reference to it. Thats an operator+= with a misleading name. If you expect your code to create another instance and return that you need to go some steps back and read about basics such as references.

Fortunately, once you have a operator+= and a copy constructor, using that to implement an operator+ is straight-forward:

Container operator+(const Container& other) {
     Container result{*this};
     result += other;
     return result;
}

For more on operator overloading see here: What are the basic rules and idioms for operator overloading?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185