views:

90

answers:

2
//output is "01234 00000" but the output should be or what I want it to be is 
// "01234 01234" because of the assignment overloaded operator
#include <iostream>
using namespace std;
class IntArray
{
public:
  IntArray() : size(10), used(0) { a= new int[10]; }
  IntArray(int s) : size(s), used(0) { a= new int[s]; }
  int& operator[]( int index );
  IntArray& operator  =( const IntArray& rightside );
  ~IntArray() { delete [] a; }
private:
  int *a;
  int size;
  int used;//for array position
};

int main()
{
  IntArray copy;
  if( 2>1)
    {
      IntArray arr(5);
      for( int k=0; k<5; k++)
        arr[k]=k;

      copy = arr;
      for( int j=0; j<5; j++)
        cout<<arr[j];
    }
  cout<<" ";
  for( int j=0; j<5; j++)
    cout<<copy[j];

  return 0;
}

int& IntArray::operator[]( int index )
{
  if( index >= size )
    cout<<"ilegal index in IntArray"<<endl;

  return a[index];
}
IntArray& IntArray::operator =( const IntArray& rightside )
{
  if( size != rightside.size )//also checks if on both side same object
    {
      delete [] a;
      a= new int[rightside.size];
    }
  size=rightside.size;
  used=rightside.used;
  for( int i = 0; i < used; i++ )
    a[i]=rightside.a[i];
  return *this;
}
+2  A: 

Where are you incrementing used

Jasmeet
+4  A: 

I think that the problem is that nowhere in your code sets used to anything other than 0 so when you loop from 0 to used nothing is copied.

Do you mean to set used when you assign to an element in operator[] ?

Also, if it's necessary to define a destructor and a copy-assignment operator then you usually (and in this case) need to supply a copy-constructor as well.

Charles Bailey
yeah i that was the problem that I had for a hours, thank you.