Dynamic Constructors in C++: Implementation & Examples

Published: 6 Mar 2025 | Reading Time: 3 min read

Overview

Dynamic constructors in C++ are a powerful feature that allows for the dynamic allocation of memory during a program's runtime. This capability is used when the size or number of objects cannot be determined at compile time, enabling more flexible and efficient memory management. This article explores the concept of dynamic constructors, their implementation, benefits, and best practices.

Table of Contents

What are Constructors in C++?

In C++, constructors are special member functions invoked automatically when a class object is created. They are essential for initialising the object's data members. There are four primary types of constructors in C++:

1. Default Constructor

A default constructor is a constructor that does not take any parameters and initialises an object with default values.

2. Parameterized Constructor

A parameterised constructor accepts one or more arguments to initialise an object with specific values, allowing for flexible object creation.

3. Copy Constructor

A copy constructor initialises a new object as a copy of an existing object of the same class, ensuring that the copied object's data members are appropriately initialised.

4. Move Constructor

A move constructor enables the efficient transfer of resources from one object to another without making a copy. This is particularly useful for managing dynamically allocated memory and optimising performance by avoiding unnecessary data copying.

Characteristics of Constructors

Here are the characteristics of constructors in C++:

What is a Dynamic Constructor?

When memory is allocated during a program's run using the new keyword in a constructor, it is called a dynamic constructor. This allows the program to create objects with sizes that are not known until the program is actually running. This means that the memory for the object's data members is allocated on the heap rather than on the stack, allowing for more flexible memory usage.

Syntax

class ClassName {
private:
    // Private members
public:
    // Dynamic constructor
    ClassName(/* parameters */) {
        // Initialization using new keyword
    }
    ~ClassName() {
        // Destructor to deallocate memory
    }
};

Implementation of Dynamic Constructors

To implement dynamic constructors, you need to follow the below steps:

Step 1: Define the Class and Data Members

To define a dynamic constructor, declare your class and its data members. Include pointers for any dynamically allocated memory.

#include <iostream>
using namespace std;

class MyClass {
private:
    int* data;
    int size;

public:
    MyClass(int s); // Dynamic constructor declaration
    ~MyClass(); // Destructor to free memory
    void display();
};

Step 2: Implement the Dynamic Constructor

Implement the dynamic constructor to allocate memory using new and initialise the object.

MyClass::MyClass(int s) {
    size = s;
    data = new int[size]; // Dynamically allocate memory
    for (int i = 0; i < size; i++) {
        data[i] = i + 1; // Initialize array elements
    }
}

Step 3: Implement the Destructor

Always implement a destructor to free any dynamically allocated memory and prevent memory leaks.

MyClass::~MyClass() {
    delete[] data; // Deallocate memory
}

Practical Examples of Dynamic Constructors

Here are the examples of dynamic constructors in C++:

1. Dynamic Memory Allocation Using Constructor

Code

#include <iostream>
using namespace std;

class DynamicArray {
private:
    int* arr;
    int size;

public:
    DynamicArray(int n) {
        size = n;
        arr = new int[size];  // Dynamically allocate memory
    }

    ~DynamicArray() {
        delete[] arr;  // Deallocate memory
    }

    void initializeArray() {
        for (int i = 0; i < size; i++) arr[i] = i + 1;
    }

    void displayArray() {
        for (int i = 0; i < size; i++) cout << arr[i] << " ";
        cout << endl;
    }
};

int main() {
    DynamicArray obj(5);
    obj.initializeArray();
    obj.displayArray();
}

Output

1 2 3 4 5

Explanation

2. Dynamic Constructor with Array of Objects

Code

#include <iostream>
using namespace std;

class Employee {
public:
    Employee(string name, int id) : name(name), id(id) {}
    void display() { cout << "ID: " << id << ", Name: " << name << endl; }

private:
    string name;
    int id;
};

class EmployeeList {
private:
    Employee** employees;
    int size;

public:
    EmployeeList(int n) {
        size = n;
        employees = new Employee*[size];
        for (int i = 0; i < size; i++) {
            employees[i] = new Employee("Employee_" + to_string(i+1), 1000 + i);
        }
    }

    ~EmployeeList() {
        for (int i = 0; i < size; i++) delete employees[i];
        delete[] employees;
    }

    void displayEmployees() {
        for (int i = 0; i < size; i++) employees[i]->display();
    }
};

int main() {
    EmployeeList list(3);
    list.displayEmployees();
}

Output

ID: 1000, Name: Employee_1
ID: 1001, Name: Employee_2
ID: 1002, Name: Employee_3

Explanation

3. Using Dynamic Constructor for 2D Arrays

Code

#include <iostream>
using namespace std;

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

public:
    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];
    }

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

    void initializeMatrix() {
        int val = 1;
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++) arr[i][j] = val++;
    }

    void displayMatrix() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) cout << arr[i][j] << " ";
            cout << endl;
        }
    }
};

int main() {
    Matrix m(3, 3);
    m.initializeMatrix();
    m.displayMatrix();
}

Output

1 2 3
4 5 6
7 8 9

Explanation

Benefits of Dynamic Constructors

Here are the key benefits of using dynamic constructors:

Best Practices of Dynamic Constructors

Here are the best practices of dynamic constructors in C++:

Conclusion

In conclusion, dynamic constructors in C++ provide a flexible mechanism for initialising objects with dynamically allocated memory at runtime. This feature allows developers to create more efficient and adaptable applications that respond to varying conditions and user inputs. Proper implementation ensures dynamic constructors enhance performance and maintainability in C++ programming.

Frequently Asked Questions

1. What are objects created dynamically in C++?

2. How is dynamic initialisation of objects achieved through constructors in C++?

Dynamic initialisation occurs when an object is created with parameters, often in the constructor.

Example: MyClass *obj = new MyClass(param1, param2);—the constructor runs with the passed parameters

3. What are the reasons for using dynamic memory allocation in C++?

4. What is meant by dynamic type in C++?

Dynamic type refers to the actual type of an object at runtime, especially with polymorphism.

For example, a base class pointer can point to derived class objects, and the dynamic type determines which method to call at runtime.

Related Articles


About NxtWave: NxtWave provides industry-recognized IT training and certifications. Learn more at ccbp.in or contact [email protected]