Dynamic Initialization of Objects in C++
In this article, you will learn about the dynamic initialization of objects in C++ with their examples.
Introduction:
In C++, objects are instances of classes that can be created differently. One common way is through dynamic initialization. Dynamic initialization refers to creating objects on the heap memory at runtime using pointers. It provides more flexibility and control over the object's lifecycle than static initialization.
Let's see the concept step by step:
1. Static Initialization:
In C++, you can create objects using regular variable declarations, as shown below:
MyClassobj; // Static initialization
The obj is created on the stack memory, and its memory is managed automatically. It exists only within the scope it was declared in.
2. Dynamic Initialization:
Dynamic initialization involves creating objects on the heap memory using pointers. It allows you to control the object's lifetime and manage its memory explicitly.
MyClass *ptr = new MyClass; // Dynamic initialization
In this case, ptr is a pointer to a dynamically allocated object of the MyClass class. The new keyword allocates memory on the heap and constructs the object. Remember that you are responsible for deallocating this memory when you're done using the object to prevent memory leaks.
3. Cleaning Up:
Dynamic objects require explicit cleanup with the delete keyword, in contrast to static initialization, where objects are automatically destroyed when they leave their scope:
Delete ptr; // Deallocate memory and destroy object
Deleting the object before the pointer goes out of scope will result in a memory leak.
Algorithm:
Step-1: Include Required Header:
- Include the necessary Header file to access console output functionality.
Step 2: Define a Class:
- Define a class named MyClass.
Step 3: Create Constructor and Destructor:
- Inside MyClass:
- Create a constructor to indicate when an object is constructed.
- Create a destructor to indicate when an object is destructed.
Step-4: Begin Main() Function:
- Start the main program.
Step-5: Dynamic Initialization:
- Declare a pointer ptr of type MyClass*.
- Allocate memory for an object of MyClass using the new keyword.
- Print a message to indicate the constructor call.
Step-6: Use the Object:
- It perform operations involving the ptr object.
Step-7: Clean Up:
- Deallocate the memory using the delete keyword.
- Print a message to indicate the destructor call.
Step-8: End Main() Function:
- Finally, end the main() function.
Program:
Let's take an example to understand the use of the dynamic initialization of objects in C++.
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout<< "MyClass constructor called." <<std::endl;
}
~MyClass() {
std::cout<< "MyClass destructor called." <<std::endl;
}
};
int main() {
// Dynamic initialization
MyClass *ptr = new MyClass;
// Use the object...
// Clean up
delete ptr;
return 0;
}
Output:
MyClass constructor called.
MyClass destructor called.
Explanation:
1. Include Header:
The code starts by including the necessary header file, <iostream>, which provides input and output stream functionality.
2. Define a Class MyClass:
After that, a class named MyClass is defined. It has a constructor and a destructor.
The constructor (MyClass()) is a special function that is automatically called when an object of the class is created. In this case, the constructor prints the message "MyClass constructor called".
The destructor (~MyClass()) is another special function that is automatically called when an object of the class goes out of scope or is explicitly deleted. In this case, the destructor prints the message "MyClass destructor called".
3. Main Function:
The main part of the program begins with the main() function, which serves as the entry point for the program's execution.
4. Dynamic Initialization:
A pointer ptr of type MyClass* is declared. This pointer will be used to store the memory address of a dynamically allocated object of the MyClass class.
The new keyword is used to allocate memory on the heap for an object of the MyClass class. This memory allocation also triggers the constructor of the class to be called, printing "MyClass constructor called".
5. Use the Object:
At this point, you have an object created using dynamic initialization. The comment "Use the object..." indicates that you can perform operations involving the ptr object. This part is left empty in the code because it's up to you to define what operations you want to perform with the object.
6. Clean Up:
The previously allocated memory for the object referenced by ptr can be deallocated using the delete keyword. This operation also triggers the destructor of the MyClass class to be called, printing "MyClass destructor called".
7. Return Statement:
The main function ends by returning the value 0, indicating that the program executed without errors.
Complexity analysis:
Time Complexity:
1. Dynamic Initialization (new MyClass):
Time Complexity: O(1)
Allocating memory for a single object using new involves a constant amount of time. The time complexity is independent of the number of objects being created.
2. Destructor Call (delete ptr):
Time Complexity: O(1)
The delete operation deallocates memory for a single object. Like dynamic initialization, this operation takes a constant amount of time.
The time complexity of the given code is constant, O(1), since both dynamic initialization and destructor calls involve operations that take a constant amount of time.
Space Complexity:
1. Dynamic Initialization (ptr = new MyClass):
Space Complexity: O(1)
The memory required to store the pointer ptr is constant and doesn't depend on the number of objects created. The space complexity remains constant.
2. Destructor Call (delete ptr):
Space Complexity: O(1)
Similarly, the memory space needed for the pointer ptr remains constant regardless of the number of objects, so the space complexity remains constant.
The space complexity of the given code is also constant, O(1), as the memory consumption doesn't change based on the number of objects created.