Can't manage to display the last array

Viewed 40

I have these code:

#include<iostream>
#include<iomanip>

using namespace std;

class Array {

private:
        
        static const int size = 100;
        int arr[size];
public:
        
        Array();
        void display();
        Array& operator+(const Array& arr);

};


Array::Array()
{
        for (int i = 0; i < size; i++)
        {
                arr[i] = rand() % 99 + 1;
        }
}
void Array::display()
{
        for (int i = 0; i < size; i++)
        {

                cout << setw(5) << arr[i];
                if ((i + 1) % 10 == 0)
                        cout << endl;
        }
}

Array & Array::operator+(const Array & arr)
{
        Array temp;
        for (int i = 0; i < size; i++)
        {
                temp.arr[i] = this->arr[i] + arr.arr[i];
        }
        return temp;
}


int main()
{
        srand(time(NULL));

        Array arr1, arr2;

        cout << "arreglo 1:\n";
        arr1.display();
        cout << endl;

        cout << "arreglo 2:\n";
        arr2.display();
        cout << endl;

        //adding both arr HERE IS MY PROBLEM
        Array arr3 = arr1 + arr2; 
        cout << "Suma de arreglo 1 y arreglo 2: " << endl;
        arr3.display();
        cout << endl;
        return 0;
}

Somehow it can't manage to display Array arr3 = arr1 + arr2.

1 Answers
Array & Array::operator+(const Array & arr)
{
        Array temp;
        ...
        return temp;
}

This returns a reference to an object that goes out of scope and is destroyed after the function returns. As a general rule you should not return addresses of or references to local variables.

Remove the & so it returns a new Array instead:

Array Array::operator+(const Array & arr)
Related