How to Dynamically allocate objects in arrays using C++

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/dynamically-allocate-objects-arrays-using-c/

In the previous topic memory for array of objects was static as the memory was allocated at compile time. To allocate memory dynamically or at run time, we use an array of pointers which can be created as follows:

ClassName *array-name[size];

 

Memory allocated for an array of pointers is far less than memory allocated for an array of objects. We can create an object at run time using the new operator as follows:

array-name[index] = new ClassName;

 

After dynamically allocating memory for an object we access the members using the -> operator as follows:

array-name[index]->member;

 

Below example demonstrates how to dynamically allocate memory for an array of objects:

 

Objects As Function Arguments

Like variables, objects can also be passed using pass-by-value, pass-by-reference, and pass-by-address. In pass-by-value we pass the copy of an object to a function. In pass-by-reference we pass a reference to the existing object. In pass-by-address we pass the address of an existing object. Following program demonstrates all three methods of passing objects as function arguments:

 

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/dynamically-allocate-objects-arrays-using-c/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger