When I overload the assignment operator for my simple class array, I get the wrong answer I espect

Posted by user299648 on Stack Overflow See other posts from Stack Overflow or by user299648
Published on 2010-05-04T06:59:34Z Indexed on 2010/05/04 7:08 UTC
Read the original article Hit count: 208

//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;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about operator-overloading