๐ What is Dynamic Initialization of Objects?
Dynamic Initialization refers to the process of initializing objects at runtime, rather than at compile time.
It allows values to be provided by the user or calculated during program execution, and then used to initialize an object through constructors.
๐ Key Points:
- Performed using constructors.
- Initialization happens using runtime values (like user input or expressions).
- Commonly used with parameterized constructors.
๐งช Example: Dynamic Initialization using User Input
#include <iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Parameterized constructor
Student(int r, string n) {
roll = r;
name = n;
}
void display() {
cout << "Roll No: " << roll << ", Name: " << name << endl;
}
};
int main() {
int r;
string n;
cout << "Enter Roll No: ";
cin >> r;
cout << "Enter Name: ";
cin >> n;
Student s(r, n); // Dynamic initialization using runtime values
s.display();
return 0;
}
๐ฏ Output (example):
Enter Roll No: 101
Enter Name: Alice
Roll No: 101, Name: Alice
๐ง Real-Life Analogy
Imagine you’re filling out an online form. You enter your name and roll number at runtime, and the system uses those inputs to create your student record. This is dynamic initialization.
๐ ๏ธ Dynamic Initialization with Calculations
You can also dynamically initialize an object using calculated values.
class Rectangle {
int area;
public:
Rectangle(int l, int b) {
area = l * b; // Value calculated at runtime
}
void display() {
cout << "Area = " << area << endl;
}
};
int main() {
int length = 10;
int breadth = 5;
Rectangle r(length, breadth); // Initialized using dynamic values
r.display();
return 0;
}
๐ Summary
- Dynamic Initialization means initializing objects at runtime using constructors.
- Useful when values are obtained from user input, file, or computations.
- Achieved using parameterized constructors.
- Makes programs more interactive and flexible.