Question: Q2: its possible to make a class that acts like an array. The CLARRAY example shown here is a complete program that shows one way

Q2: its possible to make a class that acts like an array. The CLARRAY example shown here is a complete program that shows one way to create your own array class:

// clarray.cpp

// creates array class

#include

using namespace std;

////////////////////////////////////////////////////////////////

class Array //models a normal C++ array

{

private:

int* ptr; //pointer to Array contents

int size; //size of Array

public:

Array(int s) //one-argument constructor

{

size = s; //argument is size of Array

ptr = new int[s]; //make space for Array

}

~Array() //destructor

{

delete[] ptr;

}

int& operator [] (int j) //overloaded subscript operator

{

return *(ptr+j);

}

};

////////////////////////////////////////////////////////////////

int main()

{

const int ASIZE = 10; //size of array

Array arr(ASIZE); //make an array

for(int j=0; j

{

arr[j] = j*j;

}

for(int j=0; j

{

cout << arr[j] <<" ";

cout << endl;

}

return 0;

}

The output of this program is

0 1 4 9 16 25 36 49 64 81

Starting with CLARRAY, add an overloaded assignment operator and an overloaded copy constructor to the Array class. Then add statements such as

Array arr2 (arr1);

and

arr3 = arr1;

to the main() program to test whether these overloaded operators work. The copy constructor should create an entirely new Array object with its own memory for storing array elements. Both the copy constructor and the assignment operator should copy the contents of the old Array object to the new one. What happens if you assign an Array of one size to an Array of a different size?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!