w3resource

C++ Dynamic Memory Allocation: Creating an array of objects with new operator

C++ Dynamic Memory Allocation: Exercise-6 with Solution

Write a C++ program to dynamically create an array of objects using the new operator.

Sample Solution:

C Code:

#include <iostream>  // Including the Input/Output Stream Library

class MyClass {  // Declaration of a class named MyClass
public:
  void displayMessage() {  // Public member function within the class MyClass
    std::cout << "Dynamic object!" << std::endl;  // Outputting a message
  }
};

int main() {
  // Get the size of the array from the user
  int size;  // Declaring a variable to store the size of the array
  std::cout << "Input the size of the array: ";  // Prompting the user to enter the size of the array
  std::cin >> size;  // Reading the size of the array entered by the user

  // Create a dynamic array of MyClass objects
  MyClass * dynamicArray = new MyClass[size];  // Dynamically allocating memory for an array of MyClass objects of 'size'

  // Access and use the objects in the dynamic array
  for (int i = 0; i < size; i++) {  // Looping through each element of the dynamic array
    dynamicArray[i].displayMessage();  // Accessing and invoking the displayMessage function for each MyClass object
  }

  // Deallocate the dynamic array
  delete[] dynamicArray;  // Deallocating the memory occupied by the dynamic array

  return 0;  // Returning 0 to indicate successful execution of the program
}

Sample Output:

Input the size of the array: 10
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!
Dynamic object!

Explanation:

In the above exercise,

  • We define a class called MyClass with a member function displayMessage() that outputs a message.
  • Inside the main() function, prompt the user to input the array size using std::cin. We store the size in the size variable.
  • We then use the new operator to dynamically create an array of MyClass objects and assign its address to a pointer called dynamicArray. This dynamically created array resides in the heap memory.
  • Next we use a for loop to access and use each object in the dynamic array. In this example, we call the displayMessage() member function of each object.
  • Finally, we deallocate the dynamically created array using the delete[] operator to free the memory occupied by the array.

Flowchart:

Flowchart: Creating an array of objects with new operator .

CPP Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Creating Objects with new Operator.
Next C++ Exercise: Allocating memory for structure and user input.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.