0

I have created this simple object in C++:

class Array
{
    int Size;
    int * pArr;

public:
    explicit Array(int InSize = 0)
    {
        Size=InSize;
        if (Size) 
            pArr = new int[Size];
        else 
            pArr = NULL;
    }

    Array(const Array & InArray)
    {       
        Size=InArray.Size;
        if (Size)
            pArr=new int[Size];
        else
            pArr=NULL;
    }

    ~Array()
    {
        if (pArr)
        {
            delete []pArr;
            Size=0;
        }     
    }
};

I am trying to overload the + operator in the following manner:

Array operator+(const Array &LOpArray,const Array &ROpArray)
{
    int MinSize=LOpArray.Size<ROpArray.Size ? LOpArray.Size : ROpArray.Size ;
    Array ResArray;

    if (LOpArray.Size<ROpArray.Size)
        ResArray=ROpArray;
    else
        ResArray=LOpArray;
    for (int i=0;i<MinSize;i++)
        ResArray.pArr[i]=LOpArray.pArr[i]+ROpArray.pArr[i];
    return(ResArray);
}

Assignment is defined as:

Array& Array::operator=(const Array &ROpArray)
{
    if (pArr!=ROpArray.pArr)
    {          
        Size=ROpArray.Size;
        pArr=new int[Size];
        for (int i=0;i<Size;i++)
            pArr[i]=ROpArray.pArr[i];
    }
    return (*this);
}

The problem is when I use it like :

Array A1(20),A2(8),A4;

....//initializing pointer contents

A4=A1+A2;

then A4 has correct values (i.e. size=20 and new,non NULL, int pointer) but all the pointed values have garbage values. debugging showed that in the operator+ function values are actually correct but they are deleted when returning from the operator+ function

What am I doing wrong?

2
  • 1
    Please edit your post for formatting. I've done the first few lines to show you what it's supposed to look like. Don't use tabs. Commented Dec 4, 2012 at 21:05
  • I have re-edited it....or so I hope. Commented Dec 4, 2012 at 21:22

1 Answer 1

2

I can see a couple of problems:

  1. The copy constructor fails to copy the data.
  2. operator= leaks memory (this doesn't have anything to do with your problem, but is worth fixing).
Sign up to request clarification or add additional context in comments.

1 Comment

1.Have fixed copy constructor - it's solved the problem....Thanx!!! 2.What do you mean by "leaks memory"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.