0

I want to overload + operator so that you can add two objects of type myfunnyarray(data type which behave like a built-in C++ array of integers). The resulting object should be the concatenation of the arrays of the two operands of addition. However for some reason the result is consisting of garbage values.

here is my code :

#include <iostream>
using namespace std;

class myfunnyarray{  
    int *x;
    public:
    myfunnyarray(int size){
        x = new int[size];
        for(int i=0;i<size;i++)
            x[i]=0;
    }
    myfunnyarray(int size, int value){
        x = new int[size];
        for(int i=0;i<size;i++)
            x[i]=value;
    }
  
    ~myfunnyarray(){
        delete [] x;
    }
    myfunnyarray operator+(myfunnyarray obj)
    {
        int size = sizeof(x);
        int temp = sizeof(obj.x);
        myfunnyarray result(size + temp);
        cout<<result<<endl;
        for (int i = 0; i < size; i++)
        {
            result.x[i] = x[i];
            cout<<result<<endl;
        }
        for (int i = size; i < size + temp; i++)
        {
            result.x[i] = obj.x[i - size];
        }
        return result;
    }
    friend ostream &operator<< (ostream &out, myfunnyarray o);
};
   ostream &operator<< (ostream &out, myfunnyarray o){
    for (int i = 0; i < sizeof(o.x)+1; i++)
    {
        out << o.x[i];
        if (i < sizeof(o.x) )
        {
            out << ",";
        }
    }
    return out;
}
int main(){
    myfunnyarray s(5);
    cout<<saim<<endl;
    myfunnyarray p(5,10);
    cout<<paim<<endl;
    myfunnyarray q = s +p;
    cout<<q; 
}
  • 1
    `sizeof` operator returns not the number of elements but the size (in bytes) of the pointers. You have to hold the number of elements separately. – MikeCAT Apr 18 '21 at 13:16
  • 1
    This will fail miserably, no matter how you write your `operator +`, since your `myfunnyarray` class violates the [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). You are returning copies of `myfunnyarray` in `operator +`. Fix the copy semantics of your class first, and then concern yourself with overloading of operators. Also, `operator +` should be taking the argument by `const` reference, not by value. – PaulMcKenzie Apr 18 '21 at 13:21
  • At the duplicate link concerning the rule of 3, go to the **Managing resources** section and read it carefully. Your class makes the same mistakes pointed out in that section. – PaulMcKenzie Apr 18 '21 at 13:43

0 Answers0