Dynamic Initialization Using Constructors in C++



Dynamic Initialization Using Constructors

In C++, Dynamic initialization is the process of initializing variables or objects at runtime using constructors.

Where constructors play an important role in object creation and can be used to initialize both static and dynamic data members of a class.

While creating an object, its constructor is called and if the constructor contains logic to initialize the data members with values, is known as dynamic initialization. This is helpful because here the value is calculated, retrieved, or determined during runtime, which is more flexible than static initialization.

Syntax

Here is the following syntax for dynamic initialization using constructors.

 ClassName* objectName = new ClassName(constructor_arguments); 

Here, ClassName is the class type.

objectName is the pointer to the object.

constructor_arguments are the arguments passed to the constructor.

Example of Dynamic Initialization Using Constructors

Here is the following example of dynamic initialization using constructors.

 #include <iostream> using namespace std; class Rectangle { public: int width, height; // Constructor to initialize width and height Rectangle(int w, int h) : width(w), height(h) {} void display() { cout << "Width: " << width << ", Height: " << height << endl; } }; int main() { // Dynamically creating a Rectangle object using the constructor Rectangle* rect = new Rectangle(10, 5); // Display the values rect->display(); // Deallocate memory delete rect; return 0; } 

Output

 Width: 10, Height: 5 

Explanation

  • The new Rectangle(10, 5) dynamically created a Rectangle object having width 10 and height 5 using the constructor.
  • This rect->display() is displaying the rectangle's dimensions.
  • The delete rect; deallocates the memory used by the Rectangle object.

Why Use Constructors for Dynamic Initialization?

  • Allows initialization with values known only at runtime.
  • Simplifies object creation and initialization logic.
  • Combines initialization and validation in a single step.

Using a constructor to initialize dynamically within C++ makes it so much easier to create an object where the values get determined only at runtime. Encapsulation of initialization logic within the constructor makes the code clean, efficient, and more maintainable; use it whenever object initialization depends upon runtime data.

Advertisements
close