Home > OS >  The following code is supposed to return true if i compare a1 with a2. But it is returning false. Ki
The following code is supposed to return true if i compare a1 with a2. But it is returning false. Ki

Time:04-17

#include<iostream>
#include<cstring>

using namespace std;

class Array {
private:
    int* array;
    int s;
public:
    Array()
        {
            array = NULL;
            s = 0;
                    
        }
    Array(int size)
        {
            size = (size > 0 ? size : 10);
            array = new int[size]; 
            for (int i = 0; i < size; i  )
                array[i] = 0;
                    
        }
    Array(int* arr, int size)
        {
            for (int i = 0; i < size; i  )
            {
                *(arr   i) = *(array   i);
            
            }
        }
    Array(const Array& a):s(a.s)
        {
            array = new int[s];
            for (int i = 0; i < s; i  )
                array[i] = a.array[i];
                    
        }
    int& operator[](int i)
        {
            return array[i];
        }
    const Array& operator=(const Array& obj)
        {
            if (&obj != this) { 
                if (s != obj.s) {
                    delete[] array; 
                    s = obj.s;
                    array = new int[s]; 
                }
            
            }
            for (int i = 0; i < s; i  )
                array[i] = obj.array[i];
            return *this;
        }
    bool operator==(const Array&obj)const
        {
            if (s != obj.s)
                return false;
            for (int i = 0; i < s; i  ) {
                if (array[i] != obj.array[i])
                    return false;
            }
            return true;
        }
                
    ~Array() {
        delete[] array;
    }
};

int main()
{
    Array a1(5);
    int arr[] = { 1,2,3,4,5 };
    Array a2(arr, 5);
    a1 = a2;
}

I am trying to run above program which is supposed to return true if I compare a1 and a2.but when I run this program I am getting false. Kindly check the overloaded operators and let me know where is the mistake. I have overloaded both assignment and equal operators but still I am not getting the actual output. Thank you in advance.

CodePudding user response:

Three issues. The first is that you never allocated memory in the Array(int*, int) constructor for the array. The second is that this assignment...

*(arr   i) = *(array   i);

should be

*(array   i) = *(arr   i);

or even better

array[i] = arr[i];

The third is that you are neglecting to assign s to the length of the array in some of your constructors.

  • Related