Dynamic Constructor in C++ with Examples

A dynamic constructor in C++ is a constructor that allocates memory dynamically while creating an object. It uses dynamic memory allocation to reserve memory at runtime according to the requirements of the program. Dynamic constructors are useful when the amount of memory required by an object is not known in advance.

C++ में Dynamic Constructor ऐसा constructor होता है जो object बनाते समय runtime पर dynamically memory allocate करता है। इसका उपयोग तब किया जाता है जब आवश्यक memory का आकार पहले से निश्चित नहीं होता है।

What is a Dynamic Constructor in C++?

A dynamic constructor is a constructor that uses dynamic memory allocation, generally through the new operator, to allocate memory for an object's data members.

Definition: A dynamic constructor is a constructor that allocates memory dynamically during object initialization.

परिभाषा: Dynamic Constructor वह constructor है जो object initialization के समय dynamically memory allocate करता है।

In C++, the new operator allocates memory dynamically and returns a pointer to the allocated memory.

C++ में new operator runtime पर memory allocate करता है और allocated memory का address pointer के रूप में return करता है।

Syntax of Dynamic Constructor

class ClassName
{
private:
data_type *ptr;
public:
ClassName()
{
ptr = new data_type;
}
};

Here:

  • ptr is a pointer data member.

  • new allocates memory dynamically.

  • The allocated memory is accessed using the pointer.

यहाँ ptr एक pointer variable है और new operator इसकी सहायता से runtime पर memory allocate करता है।

Example 1: Dynamic Constructor Using new Operator

The following program demonstrates a dynamic constructor that allocates memory for an integer variable.

#include <iostream>
using namespace std;
class Number
{
private:
int *ptr;
public:
Number(int n)
{
ptr = new int;
*ptr = n;
}
void display()
{
cout << "Value = " << *ptr << endl;
}
~Number()
{
delete ptr;
}
};
int main()
{
Number n1(100);
n1.display();
return 0;
}

Output:

Value = 100

Explanation:

  1. The Number class contains an integer pointer named ptr.

  2. The constructor allocates memory using new int.

  3. The value passed through the constructor is stored at the allocated memory location.

  4. The display() function accesses the value using the pointer.

  5. The destructor releases the allocated memory using delete.

व्याख्या:

  1. Number class में ptr नाम का integer pointer है।

  2. Constructor new int की सहायता से memory allocate करता है।

  3. Constructor को दिया गया value allocated memory में store किया जाता है।

  4. display() function pointer की सहायता से value प्रदर्शित करता है।

  5. Destructor delete operator से allocated memory release करता है।

Example 2: Dynamic Constructor Using Dynamic Array

A constructor can also allocate memory for an array dynamically. The array size can be supplied when the object is created.

Constructor की सहायता से dynamically array के लिए भी memory allocate की जा सकती है। Array का size object बनाते समय दिया जा सकता है।

#include <iostream>
using namespace std;
class Array
{
private:
int *arr;
int size;
public:
Array(int n)
{
size = n;
arr = new int[size];
}
void input()
{
cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
}
void display()
{
cout << "Array elements: ";
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
~Array()
{
delete[] arr;
}
};
int main()
{
Array a1(5);
a1.input();
a1.display();
return 0;
}

Sample Input:

Enter 5 elements: 10 20 30 40 50

Output:

Array elements: 10 20 30 40 50

Explanation:

  1. The Array class contains an integer pointer arr and an integer variable size.

  2. The constructor receives the array size as an argument.

  3. The statement arr = new int[size]; dynamically allocates memory for the array.

  4. The input() function accepts array elements.

  5. The display() function displays the elements.

  6. The destructor releases the dynamically allocated array using delete[].

व्याख्या:

  1. Array class में arr pointer और size variable हैं।

  2. Constructor array का size argument के रूप में प्राप्त करता है।

  3. new int[size] की सहायता से runtime पर array के लिए memory allocate होती है।

  4. input() function array elements input करता है।

  5. display() function elements प्रदर्शित करता है।

  6. Destructor delete[] का उपयोग करके array की memory release करता है।

Example 3: Dynamic Constructor for Student Marks

The following program dynamically allocates memory to store marks of a student.

इस program में student के marks store करने के लिए dynamically memory allocate की जाती है।

#include <iostream>
using namespace std;
class Student
{
private:
int rollNo;
int subjects;
float *marks;
public:
Student(int r, int n)
{
rollNo = r;
subjects = n;
marks = new float[subjects];
}
void input()
{
cout << "Enter marks of " << subjects << " subjects: ";
for (int i = 0; i < subjects; i++)
{
cin >> marks[i];
}
}
void display()
{
float total = 0;
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: ";
for (int i = 0; i < subjects; i++)
{
cout << marks[i] << " ";
total += marks[i];
}
cout << endl;
cout << "Total Marks: " << total << endl;
}
~Student()
{
delete[] marks;
}
};
int main()
{
Student s1(101, 3);
s1.input();
s1.display();
return 0;
}

Sample Input:

Enter marks of 3 subjects: 80 75 90

Output:

Roll Number: 101
Marks: 80 75 90
Total Marks: 245

Explanation:

  • The constructor accepts the roll number and number of subjects.

  • Memory is dynamically allocated for the marks array.

  • The input() function accepts marks at runtime.

  • The display() function calculates and displays total marks.

  • The destructor releases the allocated array memory.

इस उदाहरण में constructor roll number और subjects की संख्या प्राप्त करता है। उसके बाद marks store करने के लिए dynamic array allocate किया जाता है।

Advantages of Dynamic Constructor

  1. Runtime Memory Allocation: Memory can be allocated according to program requirements.
    प्रोग्राम की आवश्यकता के अनुसार runtime पर memory allocate की जा सकती है।

  2. Flexible Array Size: Dynamic arrays can have sizes determined during program execution.
    Dynamic array का size program execution के समय निर्धारित किया जा सकता है।

  3. Efficient Resource Usage: Memory can be allocated when required instead of reserving a fixed-size array in advance.
    आवश्यकता पड़ने पर memory allocate की जा सकती है, जिससे पहले से fixed-size array reserve करने की जरूरत कम होती है।

  4. Object Initialization: Dynamic resources can be allocated during object construction.
    Object निर्माण के समय dynamic resources allocate किए जा सकते हैं।

Disadvantages of Dynamic Constructor

  1. Memory Management: Dynamically allocated memory must be released correctly.
    Dynamically allocated memory को सही तरीके से release करना आवश्यक है।

  2. Memory Leaks: Forgetting to release allocated memory can cause memory leaks.
    Memory release करना भूलने पर memory leak हो सकता है।

  3. Pointer Errors: Incorrect pointer handling can cause undefined behavior.
    Pointer को गलत तरीके से handle करने पर undefined behavior हो सकता है।

  4. Complexity: Dynamic memory management makes programs more complex.
    Dynamic memory management से program अधिक जटिल हो सकता है।

Dynamic Constructor vs Normal Constructor

Dynamic ConstructorNormal Constructor
Traditionally refers to a constructor that allocates dynamic memory.Initializes an object without necessarily allocating dynamic memory.
Often uses new or other dynamic allocation mechanisms.May use ordinary assignments or member initializer lists.
Commonly involves pointer data members.Does not necessarily require pointers.
Requires appropriate resource management.May not require manual memory management.

Note: Both are ordinary C++ constructors. The term dynamic constructor describes what the constructor does; it is not a separate constructor category in the C++ standard.

Modern C++: Prefer std::vector Instead of Manual Dynamic Arrays

In modern C++, std::vector is generally preferred over manually allocating arrays using new[] and releasing them using delete[].

Modern C++ में manually new[] और delete[] का उपयोग करने के बजाय std::vector का उपयोग करना सामान्यतः अधिक सुरक्षित और सुविधाजनक होता है।

Example:

#include <iostream>
#include <vector>
using namespace std;
class Array
{
private:
vector<int> arr;
public:
Array(int n) : arr(n)
{
}
void input()
{
cout << "Enter " << arr.size() << " elements: ";
for (int i = 0; i < static_cast<int>(arr.size()); i++)
{
cin >> arr[i];
}
}
void display()
{
cout << "Array elements: ";
for (int value : arr)
{
cout << value << " ";
}
cout << endl;
}
};
int main()
{
Array a1(5);
a1.input();
a1.display();
return 0;
}

Sample Input:

Enter 5 elements: 10 20 30 40 50

Output:

Array elements: 10 20 30 40 50

Here, vector<int> manages memory automatically. We do not need to write a destructor to release the vector's memory.

यहाँ vector<int> memory को अपने आप manage करता है। इसलिए vector की memory release करने के लिए अलग से destructor लिखने की आवश्यकता नहीं होती है।

Frequently Asked Questions (FAQs)

1. What is a dynamic constructor in C++?

A dynamic constructor is a traditional textbook term for a constructor that allocates memory dynamically during object creation.

2. Which operator is used for dynamic memory allocation in C++?

The new operator is used to allocate memory dynamically.

3. Why is a destructor used with a dynamic constructor?

A destructor can release dynamically allocated memory when the object is destroyed, helping prevent memory leaks.

4. What is the difference between delete and delete[]?

  • delete releases memory allocated for a single object using new.

  • delete[] releases memory allocated for an array using new[].

5. Can a dynamic constructor allocate memory for an array?

Yes. A constructor can allocate memory for an array using new[].

6. Is a dynamic constructor a separate type of constructor in C++?

No. It is a traditional educational term describing a constructor that performs dynamic memory allocation.

7. What is the modern alternative to dynamic arrays using new[]?

The standard library container std::vector is generally preferred because it manages memory automatically.

A dynamic constructor is a useful concept for understanding dynamic memory allocation in C++. It allows a constructor to allocate memory at runtime according to the requirements of an object. Understanding dynamic memory allocation, pointers, destructors and resource management is important for writing reliable C++ programs. In modern C++, standard library containers and smart pointers are generally preferred for safer memory management.

Comments

Popular posts from this blog

Important Questions (IMP) of Programming Methodologies and Data structures using C++ with OOP's Concepts

C++ Programming Syllabus Complete - From Basics to Advanced C++, including OOP and Data Structures and Algorithms (DSA)

OOP's using CPP Syllabus AND Programming Methodologies and Data Structures Using C++ (NEP 2020)