Create Dynamic 2D Array Inside a Class in C++



A dynamic 2D array is an 2D array in which the size of array is determined during runtime and stored using pointers. In this article, we will learn how to create a dynamic 2D array inside a class in C++. First of all, let's understand the problem statement.

In this problem, you need to create a class that contains a dynamic 2D array as its data member. The memory allocation and deallocation must be handled using constructor and destructor. For example:

// Create a class with dynamic 2D array
ClassMatrix m(3, 4);

// Output
Matrix of size 3 rows and 4 columns created.

// Memory automatically deallocated when object goes out of scope.

Creating Dynamic 2D Array Inside Class

To solve this problem, we need to use dynamic memory allocation concept in C++. When creating a 2D array dynamically inside a class, we should use double pointers. We allocate memory in the constructor and deallocate it in the destructor. Here we will discuss one basic approach and one safe approach to create dynamic 2D arrays inside a class.

Basic Class with Dynamic 2D Array

To implement a basic class with a dynamic 2D array, we will create a class that has a double pointer as a data member. The constructor will allocate memory for the 2D array, and the destructor will deallocate it. This is a simple implementation without deep copy support. Let's see an example:

Example

The following code shows how to create a simple class that manages its own dynamic 2D array using constructor and destructor:

#include <iostream>
using namespace std;

class Matrix {
private:
    int **arr;
    int rows, cols;

public:
    // Constructor
    Matrix(int r, int c) {
        rows = r;
        cols = c;

        arr = new int*[rows];
        for (int i = 0; i < rows; ++i) {
            arr[i] = new int[cols];
        }

        cout << "Matrix of size " << rows << " rows and " << cols << " columns created." << endl;
    }

    // Destructor
    ~Matrix() {
        for (int i = 0; i < rows; ++i) {
            delete[] arr[i];
        }
        delete[] arr;
        cout << "Matrix memory deallocated." << endl;
    }
};

int main() {
    Matrix m(3, 4); // Create 3x4 matrix
    return 0;
}

The output of the above code will be:

Matrix of size 3 rows and 4 columns created.
Matrix memory deallocated.

Safe Class with Deep Copy

In the previous example, we did not handled deep copying of the dynamic 2D array, which means if we try to copy an object of this class, it will lead to shallow copying issues, and can cause memory leaks or double deletion errors. To ensure safe copying and assignment of objects with dynamic memory, we need to implement the copy constructor and assignment operator. This technique is known as the Rule of Three in C++.

Example

The following code includes copy constructor and assignment operator for safe object copying:

#include <iostream>
using namespace std;

class Matrix {
private:
    int **arr;
    int rows, cols;

public:
    // Constructor
    Matrix(int r, int c) {
        rows = r;
        cols = c;

        arr = new int*[rows];
        for (int i = 0; i < rows; ++i) {
            arr[i] = new int[cols];
        }

        cout << "Matrix of size " << rows << "x" << cols << " created." << endl;
    }

    // Copy Constructor
    Matrix(const Matrix &other) {
        rows = other.rows;
        cols = other.cols;

        arr = new int*[rows];
        for (int i = 0; i < rows; ++i) {
            arr[i] = new int[cols];
            for (int j = 0; j < cols; ++j) {
                arr[i][j] = other.arr[i][j];
            }
        }
    }

    // Assignment Operator
    Matrix& operator=(const Matrix &other) {
        if (this == &other)
            return *this;

        // Deallocate old memory
        for (int i = 0; i < rows; ++i)
            delete[] arr[i];
        delete[] arr;

        rows = other.rows;
        cols = other.cols;

        arr = new int*[rows];
        for (int i = 0; i < rows; ++i) {
            arr[i] = new int[cols];
            for (int j = 0; j < cols; ++j) {
                arr[i][j] = other.arr[i][j];
            }
        }

        return *this;
    }

    // Destructor
    ~Matrix() {
        for (int i = 0; i < rows; ++i)
            delete[] arr[i];
        delete[] arr;

        cout << "Matrix memory deallocated." << endl;
    }
};

int main() {
    Matrix m1(2, 2);
    Matrix m2 = m1; // Uses copy constructor
    Matrix m3(1, 1);
    m3 = m1;        // Uses assignment operator
    return 0;
}

The output of the above code will be:

Matrix of size 2x2 created.
Matrix of size 2x2 created.
Matrix of size 1x1 created.
Matrix memory deallocated.
Matrix memory deallocated.
Matrix memory deallocated.
Updated on: 2025-05-28T17:37:28+05:30

807 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements