I don't understand how it works. What are lines 19-33 doing exactly? Why did they do "arraySize = obj.arraySize;" ?

#include <iostream>
#include <iomanip>
using namespace std;

class NumberArray
{
private:
  double *aPtr;
  int arraySize;
public:
  NumberArray(NumberArray &);
  NumberArray(int size, double value);
  ~NumberArray() { if (arraySize > 0) delete [] aPtr; }
  void print();
  void setValue(double value);
};


NumberArray::NumberArray(NumberArray &obj)
{
  arraySize = obj.arraySize;
  aPtr = new double[arraySize];
  for(int index = 0; index < arraySize; index++)
    aPtr[index] = obj.aPtr[index];
}  


NumberArray::NumberArray(int size, double value)
{
  arraySize = size;
  aPtr = new double[arraySize];
  setValue(value);
}


void NumberArray::setValue(double value)
{
  for(int index = 0; index < arraySize; index++)
     aPtr[index] = value;
}


void NumberArray::print()
{
  for(int index = 0; index < arraySize; index++)
    cout << aPtr[index] << "  ";
}

int main()
{  
  NumberArray first(3, 10.5);
  
  NumberArray second = first;


  cout << setprecision(2) << fixed << showpoint;
  cout << "Value stored in first object is ";
  first.print();
  cout << "\nValue stored in second object is ";
  second.print();
  cout <<  "\nOnly the value in second object will "
       <<  "be changed.\n";
  
  second.setValue(21.5);
  
  cout << "Value stored in first object is ";
  first.print();
  cout << endl << "Value stored in second object is ";
  second.print();
  return 0;
}

aPtr is a pointer to an array of "double" variables. When you want to copy one NumberArray object into another, the new object has to allocate a new array of doubles which can contain as many elements as the other object, and then copy all the elements from one array (the one in "obj") to the other (the one that just got created).

So, line-by-line:

NumberArray::NumberArray(const NumberArray& obj) //note: this is the proper way.
{
  arraySize = obj.arraySize;    //reads in the size of the array in obj
  aPtr = new double[arraySize]; //creates an array of the same size
  for(int index = 0; index < arraySize; index++) //iterates through both arrays.
    aPtr[index] = obj.aPtr[index]; //copies the content from obj.aPtr to aPtr.
}  

NumberArray::NumberArray(int size, double value)  //takes in the size of the array and the initial value for all the elements
{
  arraySize = size;             //reads in the size of the array.
  aPtr = new double[arraySize]; //creates an array of that size.
  setValue(value);              //sets all the elements of the array to "value".
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.