Custom Array Class using C++

AyoubGharbi | Jan 23, 2022 min read

Creating a custom array class in C++ can be a useful way to add additional functionality or constraints to the built-in array type. In this blog post, we will go over the steps to create a simple custom array class that can store integers and has a fixed size.

1- Define the class

First, we will create a new class called “FixedArray” to represent our custom array. In the class definition, we will include a private member variable to store the array data, as well as a private member variable to store the size of the array.

class FixedArray {
private:
    int* data;
    int size;
public:
    // constructor and other member functions will go here
};

2- Write the constructor

Next, we will add a constructor to our class to initialize the array data and size. The constructor will take in one parameter, the size of the array, and will dynamically allocate memory for the array data using the “new” operator.

class FixedArray {
private:
    int* data;
    int size;
public:
    FixedArray(int size) {
        this->size = size;
        data = new int[size];
    }
};

3- Implement the array access operator

To allow for easy access to the array data, we will implement the array access operator ([ ]). This operator will take in an index and return a reference to the element at that index. It’s important to include a check to ensure that the index is within the valid range of the array.

#include <iostream>

class FixedArray {
private:
    int* data;
    int size;
public:
    FixedArray(int size) {
        this->size = size;
        data = new int[size];
    }
    int& operator[] (int index) {
        if (index < 0 || index >= size) {
            throw std::out_of_range("Index out of range");
        }
        return data[index];
    }
};

4- Implement the destructor

To prevent memory leaks, we need to implement a destructor to deallocate the memory used by the array data when an object of the class goes out of scope.

#include <iostream>

class FixedArray {
private:
    int* data;
    int size;
public:
    FixedArray(int size) {
        this->size = size;
        data = new int[size];
    }
    ~FixedArray() {
        delete[] data;
    }
    int& operator[] (int index) {
        if (index < 0 || index >= size) {
            throw std::out_of_range("Index out of range");
        }
        return data[index];
    }
};

5- Test the class

Now that we have implemented our custom array class, we can test it by creating an object and accessing its elements.

#include <iostream>

int main() {
    FixedArray arr(5);
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;
    for (int i = 0; i < 5; i++) {
        std::cout << arr[i] << "\n";
    }
    return 0;
}