This is a part of my assignment that I was given in my college CSCI course using C++
Create a class Array, representing an arran of size n, with the private properties:
class Array {private: double * a {}; int n;
- Constructor by default
- Constructor by specifying the size of the array
- Constructor by specifying the size of the array, and the default value for all the elements in the array
- Constructor by copy
- Destructor
- Accessor: Retrieve the size of the array
I was faced with the task of defining an array using a class and the class must contain what each bullet point says. However, I am stuck on bullet point number 3. I am attempting to fill the array with default values of 0 for a[0], 1 for a1, etc. depending on the size of the array that a user inputs and sets as value n. In doing so all that my code is doing is assigning each and every element in the array with a value of 0.
#include <iostream>
using namespace std;
class MyArray {
private:
double * a {};
int n;
public:
MyArray();
explicit MyArray(int size);
MyArray(int size, double def_val);
MyArray(const MyArray & a2);
~MyArray();
int get_Size() const;
void SetElement(int i, double x);
double GetElement(int i);
void display();
};
MyArray::MyArray(int size) {
n = size;
a = new double[size];
}
MyArray::MyArray() {
a = nullptr;
n = 0;
}
double MyArray::GetElement(int i) {
return a[i];
}
void MyArray::SetElement(int i, double x) {
a[i] = x;
}
MyArray::MyArray(const MyArray & a2) {
n = a2.n;
for (int i = 0; i < n; i++) {
a[i] = a2.a[i];
}
} //constructor by copy
MyArray::~MyArray() {
delete[] a;
}
MyArray::MyArray(int size, double def_val) { //THIS IS WHERE IT SHOULD ASSIGN
n = size;
a = new double[size];
for (int i = 0; i < size; ++i) {
a[i] = i;
}
}
int MyArray::get_Size() const {
return n;
}
void MyArray::display() {
cout << "The values of the array MyArray are: " << endl;
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
int main() {
MyArray a(5);
a.display();
return 0;
}
The output is this
The values of the array MyArray are:
0 0 0 0 0