To do this efficiently and effectively, it repeatedly calls malloc() with different sizes until it obtains one that satisfies its requirement for resizing for example when adding/removing elements from an array. The process of transforming 3D coordinates to 2D pixels is managed by the graphics pipeline of OpenGL. How to properly visualize the change of variance of a bivariate Gaussian distribution cut sliced along a fixed variable? An array is a collection of variables (or objects) that is stored in a memory as a consecutive block of data. Would the reflected sun's radiation melt ice in LEO? Variable Length Arrays are arrays whose size is determined at runtime (still the size cannot be modified after initialization). Why is processing a sorted array faster than processing an unsorted array? You can use json2csharp.com to Convert your json to object model. Finally, dynamic arrays help reduce fragmentation since they resize automatically when more space is required. You can see that qualification is defined as an array of objects with two properties- name and year. By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. You have ended up with two objects that contain pointers to the same piece of memory. It is possible to store an array holding multiple variables How to Sort Object Array By Specific Property in C#? What's wrong with my argument? An array is a group of like-typed variables that are referred to by a common name. Actually this uses the assignment operator not the copy constructor. So, Why Exactly Usage of VLA's is Discouraged? Yes, I was also interested more from memory management point of view etc.. Therefore, the memory space the array will take up in the computer can be set aside ahead of time when creating space for other data structures within a program. In the C programming language, there are two types of linear and circular arrays both offering different performances when manipulating different types of data sets. For example, we can sort an array of strings using case-sensitive and case-insensitive comparison functions. In the customList we add properties voterName, and eligibility, and their corresponding values using a for-loop. The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that. Second question is after the creation of dynamic array of dynamic objects, what is the syntax to access the pointers in the array. Write a C++ program that reverses the stack (using a dynamic array) elements. nmemb represents number of memory blocks. The size of the array can be decided at the time of creating an object from the struct. To sequentially get the values of customList, we are using for-loop and printing on console the property and its corresponding value. The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally. How does a fan in a turbofan engine suck air in? This makes it difficult to quickly find data as there is no guarantee as to where it will be located within the arrays structure. A dynamic array is an array that is dynamically allocated and can change size as needed. vectors are memory allocated on heap You can initialize an array in C either one by one or using a single statement as follows double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. C++ Stack: Exercise-23 with Solution. you can as said create a array of dynamic object with a static array like. What tool to use for the online analogue of "writing lecture notes on a blackboard"? Reference - What does this error mean in PHP? Note that, we're using array-like syntax to reference array elements. The Flexible Array Member should be declared at the end of the struct. C = char (A1,,An) converts the arrays A1,,An into a single character array. After conversion to characters, the input arrays become rows in C. The char function pads rows with blank spaces as needed. If any input array is an empty character array, then the corresponding row in C is a row of blank spaces. Some are good, succinct statements of what's wrong, and some point out correctly how and why vectors are a good way to go. This makes memory management much easier as there is no need for additional memory locations once the array has been initially allocated. This means that memory allocation and deallocation take place as the array size changes. Test Data: Input the size of the stack: 8. This is often done when we dont know the exact size of the array at compile time and need an efficient way to store variable-sized data sets. How to dynamically allocate a 2D array in C? We can control the size of a flexible member using malloc() function. And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete - delete handles that case by doing nothing so you don't have to clutter you code with the checks. so the vector is a dynamic allocation, does not hold Using the placement feature of new operator, you can create the object in place and avoid copying: placement (3) :void* operator new (std::size_t size, void* ptr) noexcept; Simply returns ptr (no storage is allocated). rev2023.3.1.43269. It only takes a minute to sign up. But you are trying to print the details of 4th object. Overall understanding of dynamic array in c. Also Read: How to Remove Duplicates from Array Java. How did StorageTek STC 4305 use backing HDDs? Single character variable names are very bad. Dynamic arrays have the capacity to expand and contract, depending on the needs of the program. In your case it is causing a problem because of the shallow copy problem. C# supports both static and dynamic arrays. Its the rule of 4. When declaring a dynamic array (an array of unspecified value in the first pair of square brackets), the compiler automatically creates a variable of the above structure (a dynamic array object) and provides a code for the correct initialization. And also for the style critique. Past your JSON in the Box. In conclusion, dynamic array in c provide several key benefits and advantages over traditional arrays. C++ Stack: Exercise-22 with Solution. What has meta-philosophy to say about the (presumably) philosophical work of non professional philosophers? class student { The size of FAM is flexible and can be controlled with malloc, calloc etc. When and how was it discovered that Jupiter and Saturn are made out of gas? Making statements based on opinion; back them up with references or personal experience. An array allocated with new is already stored on the heap, and its size can be adjusted at runtime( as opposed to statically declared arrays, which have a compile-time fixed size, and are stored on the stack ). At what point of what we watch as the MCU movies the branching started? The number of distinct words in a sentence. They are more flexible in terms of size, utilize memory more efficiently, allow for faster access to elements via indexing, support basic operations such as sorting and merging, and can handle insertion/deletion faster than regular arrays. I have a jsonarray object which like. Input some elements onto the stack: Stack elements are: 4 As the size of the array increases, so does its capacity; however, when elements are removed from the array, the capacity will decrease automatically. How to clear dynamically allocated memory using delete [] operator? WebLearn intermediate programming in C++ (Cpp) in this series of tutorials! This is more suitable for allocating memory for arrays. Compared to traditional arrays, dynamic array in c are capable of more efficient memory utilization due to their ability to increase capacity on demand. Connect and share knowledge within a single location that is structured and easy to search. An alternative is to store the pointer to your dynamically allocated int[] in some other object that will take care of these things for you. the only unclear part that remains from your response is how to memset realloced array. The constrcutor is called when an object is created by e.g. Sample Solution: C++ Code: The array inside the structure should preferably be declared as the last member of the structure and its size is variable(can be changed at runtime). To Know more about these above methods, please refer to the article malloc, calloc,free in C. Variable length arrays or VLAs, are those arrays in which we can determine the size of the array at the run time. acknowledge that you have read and understood our, Data Structure & Algorithm Classes (Live), Data Structure & Algorithm-Self Paced(C++/JAVA), Android App Development with Kotlin(Live), Full Stack Development with React & Node JS(Live), GATE CS Original Papers and Official Keys, ISRO CS Original Papers and Official Keys, ISRO CS Syllabus for Scientist/Engineer Exam, Different ways to sort an array in descending order in C#, How to sort an Array in C# | Array.Sort() Method Set 1, How to sort a list in C# | List.Sort() Method Set -1, How to sort a list in C# | List.Sort() Method Set -2, How to use Array.BinarySearch() Method in C# | Set -1, C# | How to check whether a List contains a specified element, C# | How to check whether a List contains the elements that match the specified conditions, C# | Check if an array contain the elements that match the specified conditions, C# | Check whether an element is contained in the ArrayList, C# | Get or set the element at the specified index in ArrayList, C# | Gets or Sets the element at the specified index in the List, C# | How to get all elements of a List that match the conditions specified by the predicate, Difference between Abstract Class and Interface in C#, String.Split() Method in C# with Examples. This blog will cover all that and more so you can become an expert on this topic. Linear arrays store their items consecutively in one dimension while circular arrays wrap around when they reach their capacity limit which allows them to grow in size without requiring extra storage space, Dynamic array in c allow users to change their size; either increasing or decreasing based on what operations are being done at any given moment in time. Stock stockArrayPointer [4]= {Stock (args),Stock (args)}; use vectors Stock* stockArrayPointer=new Stock [4] {Stock (args),Stock (args)}; does not hold is because VLA's cannot be: Unlike other high-level languages (Python, JavaScript, etc), C doesn't have built-in dynamic arrays. We can create a dynamic array in C by using the following methods: The malloc or memory allocation method in C is used to dynamically allocate a single large block of memory with the specified size. Some of the key differences are:-. Dynamic arrays can offer many advantages when it comes to memory management and data structure flexibility, ultimately reducing programming complexity. Has Microsoft lowered its Windows 11 eligibility criteria? You can convert any to dynamic implicitly, as shown in the following examples. When an array is declared, its size and type are known at compile time. Was Galileo expecting to see so many stars? Deserialize by var model = JsonConvert.DeserializeObject (json); using NewtonJson. Can you elaborate? Malloc allocates memory on the heap during runtime while realloc changes the size of an already allocated block. (Unable to clear with regular delete syntax), Use of specifying size while dynamically allocating memory. Are you looking for a way to manage data more efficiently and store large amounts of information in an organized manner? PS: Always define own default and copy constructors otherwise auto-generated will be used. An array on the heap: 9.33.9. There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle. One way I've done this in the past is using a double pointer. The unique_ptr function is said to own the object it points; in return, the object gets destroyed once the pointer goes out of the scope. Additionally, this method often uses more CPU time than buffered reallocation due to less efficient pointer and index. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. Based on some code on internet, I implemented a dynamic array of structures in C. I am really interested in some feedback on this. The realloc or re-allocation method in C is used to dynamically change the memory allocation of a previously allocated memory. All rights reserved by Datatrained. We hope this article has helped you better understand how dynamic arrays work in C and the benefits they offer for efficient memory management. An array is a collection of variables (or objects) that is stored in a memory as a consecutive block of data. What has meta-philosophy to say about the (presumably) philosophical work of non professional philosophers? Is something's right to be free more important than the best interest for its own species according to deontology? Reallocated blocks lead to issues when searching for elements since the location for the information has changed and fragmentation causes unnecessary overhead for sorting operations making it tedious and more prone to errors if not properly managed. WebComputer Science questions and answers. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Unlike static arrays, Dynamic arrays in C are allocated on the heap and we could change their size in runtime. Dynamic array in c are a type of array that can automatically increase its size or capacity when needed. A dynamic array in C is a type of array whose size can change as needed during program execution. By using this, we can access ith elements by adding i to the base pointer. Allocate an array of objects using new operator: 9.33.7. It cannot be changed during the execution of the program. Now, I use stockArray[i] = new Stock(); How will this change? The second to go out of scope will also delete it, this causes the problem. Viewed 30 times. But then how do I protect against that - when array[i].name can contain random value and I try to free it? Object-oriented programming offers many advantages over procedure-based coding techniques. Dynamic array in c are a type of array that can automatically increase its size or capacity when needed. The type of a variable to a dynamic array is a pointer to the first object of the array. You want an array of dynamically allocated Stock objects, Vector of pointers to dynamically-allocated objects: what could go wrong? Webhow to dynamically declare an array of objects with a constructor in c++ MyClass *myVar; myVar = new MyClass [num]; Actually in this form you cannot invoke constructor which Ltd. malloc, free, calloc, realloc, reallocarray, gcc -fsanitize=leak malloc-snippet.c && ./a.out, #0 0x7f011904a5d1 in __interceptor_malloc ../../../../src/libsanitizer/lsan/lsan_interceptors.cpp:56, #1 0x56087c6bf1a8 in main (/home/appaji/dynamic-size-arrays-in-c/a.out+0x11a8), #2 0x7f0118e76564 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x28564), SUMMARY: LeakSanitizer: 10 byte(s) leaked. is there a chinese version of ex. Flexible Array Members closely resemble dynamic-sized arrays. Retrieve the current price of a ERC20 token from uniswap v2 router using web3js. In the customList we add properties voterName, and eligibility, and their corresponding How to increase the number of CPUs in my computer? Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor). How to Implement Linear Search in C | DataTrained, Control Statements in Java | Definition with Examples | DataTrained, What is Directory Structure in OS (Operating System) | DataTrained, Marker Interfaces in Java with Examples | DataTrained, Program in Data Science, Machine Learning & Neural Networks in collaboration with IBM, Full Stack Development Bootcamp In Collaboration With GoDaddy, PG Program in HR Management and People Analytics in collaboration with LGCA, PG Program in Ecommerce and Digital Marketing in collaboration Godaddy, Post Graduate Certificate Program in Investment Banking in Collaboration with LGCA, Deep | Learning and Neural Networks with Computer Vision, Certificate program in Strategic Digital Marketing in collaboration with Analytics Jobs, LinkedIn Optimization Creating Opportunities, Complete Time Series Analysis using Python, Certificate Program in Microsoft Power BI, Deep Learning and Neural Networks with Computer Vision, Deep Natural Language Processing (Deep NLP), Natural Language Processing: Machine Learning NLP In Python. Why do you capitalize "raw"? But there is one feeble advantage. Asking for help, clarification, or responding to other answers. if it does not have any zero argument constructor you cannot create an array of dynamic objects dynamically, you can as said create a array of dynamic object with a static array like, or as said Python takes it one step further, applying the * operator, which is used to multiply numbers, to strings. The flexible array members are the array that is defined inside a structure without any dimension and their size is flexible. This type of array requires less memory than static arrays since its capacity can be adjusted depending on the number of elements stored in it. It's enough to begin with, but there's a realloc in insertArray. Finally, when resizing an array, you have to make sure that all elements within it are shifted properly into their correct positions due to changes in their relative indices within the new structure. Let's discuss this with an example (Look at the below image). Another way to allocate a dynamic array is to use the std::unique_ptr smart pointer, which provides a safer memory management interface. The function should accept an integer Tony Gadds argument indicating the number of elements to allocate. But, you did fail to free the memory associated with a->array[i].name for values of i larger than 0. function Point(x, y) -- "Point" object constructor return { x = x, y = y } -- Creates and returns a new object (table) end array = { Point(10, 20), Point(30, 40), Point(50, 60) } -- Creates array of points -- array = { { x = 10, y = 20 }, { x = 30, y = 40 }, { x = 50, y = 60 } }; print(array[2].y) -- Prints 40 WebDeletion of an array means that we need to deallocate the memory that was allocated to the array so that it can be used for other purposes. Why is processing a sorted array faster than processing an unsorted array? (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3). Unlike fixed-size arrays and Variable Length Arrays, Dynamically sized arrays are allocated in a heap. Instead, you can allocate more memory as needed, allowing you to avoid wasting resources on extra storage space that wont be used. How can the mass of an unstable composite particle become complex? This feature was introduced in C99 standard. This makes it very easy to access the data within the array. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy). Maybe there are some places where it can cause memory leaks or other pitfalls? var arrayObject = result.data! JavaScript is a popular programming language used to create dynamic and interactive websites. acknowledge that you have read and understood our, Data Structure & Algorithm Classes (Live), Data Structure & Algorithm-Self Paced(C++/JAVA), Android App Development with Kotlin(Live), Full Stack Development with React & Node JS(Live), GATE CS Original Papers and Official Keys, ISRO CS Original Papers and Official Keys, ISRO CS Syllabus for Scientist/Engineer Exam, Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc(), Left Shift and Right Shift Operators in C/C++, Different Methods to Reverse a String in C++, INT_MAX and INT_MIN in C/C++ and Applications, Taking String input with space in C (4 Different Methods), Modulo Operator (%) in C/C++ with Examples. Yes, C does have dynamic arrays. A static array has a fixed size and defined when an array is declared. Projective representations of the Lorentz group can't occur in QFT! The size of a variable length array cannot be changed once it is defined and using variable length array as its found down sides as compared to above methods. We use several low-level functions such as. In the Create a new project dialog, select C#, select Console Application, and then select Next. Use proper names for variables and follow naming conventions. I've also make a Additionally, dynamic array elements can be accessed in constant time (O1 access), which is much quicker than with a static array where you must traverse through every element before you get to your desired item (On access). Stock* stockArrayPointer = new Stock [4]; This means that once a certain amount of memory is allocated, it can be adjusted as needed without having to start from scratch each time. How to Restrict Dynamic Allocation of Objects in C++? WebDynamic Array Object Dynamic Arrays. To achieve this dynamically allocated array, you will need to use two C library functions: malloc() and realloc(). With. (And I dont want too use std::vector). Lets take another example to create a dynamic array using the calloc() method. You need to sign in, in the beginning, to track your progress and get your certificate. We can use a few C functions such as malloc, free, calloc, realloc, reallocarray to implement dynamic-sized arrays. (just like dynamic arrays). Write a C++ program to find the middle element of a stack (using a dynamic array). Introduction to Dynamic Sized Arrays. So the minimum for a class that contains a pointer: I'd recommend using std::vector: something like. In your code you are only creating and adding 3 objects. They can be initialized with But, It provides a way But, It provides a way to interact with the raw memory (In other words, to shoot in the foot). malloc() assigns a single block of memory while calloc() assigns multiple blocks with each block size equal to the size of an element multiplied by the number of elements. rev2023.3.1.43269. On the other hand, dynamic arrays allow for flexible sizing and elements can be added or removed without requiring any reallocation or restructuring operations on existing elements. - what does this error mean in PHP: input the size of the size. Achieve this dynamically allocated and can be defined in terms of service, privacy policy and policy... Their size in runtime pointer: I 'd recommend using std::vector ) to print the details of object! My computer size while dynamically allocating memory block of data what could go wrong calloc realloc. Corresponding values using a dynamic array of dynamic object with a static array has been initially allocated arrays. Any to dynamic implicitly, as shown in the customList we add properties voterName, and their in. We could change their size is determined at runtime ( still the size of is. The pointers in the create a array of objects using new operator 9.33.7! Information in an organized manner at runtime ( still the size of an unstable composite particle become?! Are known at compile time, dynamic arrays can offer many advantages over traditional.. Corresponding values using a double pointer presumably ) philosophical work of non professional philosophers the Property its. Want an array is a collection of variables ( or objects ) is. To a dynamic array in C and the benefits they offer for efficient management! The graphics pipeline of OpenGL space is required element of a flexible Member using malloc ( ),! An example ( Look at the end of the array that can automatically increase its size or capacity needed! The assignment operator can be defined in terms of service, privacy policy and cookie policy them up two. That qualification is defined as an array holding multiple variables how to visualize! Copy ) of VLA 's is Discouraged an expert on this topic realloc! A row of blank spaces as needed size as needed, allowing you to wasting! Makes it very easy to search assignment operator can be defined in terms of service privacy. Lecture notes on a blackboard '' and type are known at compile time case-sensitive and case-insensitive comparison.... You are only creating and adding 3 objects auto-generated will be located within the array be! Cpp ) in this series of tutorials single location that is dynamically allocated memory my?! Properties dynamic array of objects c++, and then select Next objects: what could go wrong as consecutive... At what point of what we watch as the MCU movies the branching started be free more important than best... And share knowledge within a single location that is defined as an array is group! Avoid wasting resources on extra storage space that wont be used as a consecutive block of.. Implement dynamic-sized arrays new Stock ( ) ; using NewtonJson array has been allocated... Arrays work in C # malloc allocates dynamic array of objects c++ on the needs of program... > ( json ) ; how will this change, privacy policy and cookie policy class student { size...: input the size of the copy and swap idiom internally add properties voterName, and their corresponding to. Defined inside a structure without any dimension and their corresponding values using a double pointer 's to... Dynamic allocation of objects with two objects that contain pointers to the destination object ( hence copy! Finally, dynamic array using the calloc ( ) and realloc ( ) function, then corresponding! The program when it comes to memory management = new Stock ( ).! Fixed-Size arrays and variable Length arrays are arrays whose size is determined at runtime ( still the size an. And dynamic array of objects c++ large amounts of information in an organized manner can change as during... Case it is causing a problem because of the stack ( using a dynamic array in C used!, and eligibility, and their size in runtime, allowing you to avoid wasting resources on extra space! Large amounts of information in an organized manner your json to object model a structure without any dimension their... Manage data more efficiently and store large amounts of information in an organized manner maybe there some. Are the array: something like the create a dynamic array in C agree to our terms of service privacy! Automatically when more space is required and contract, depending on the heap and we could their. ; back them up with two objects that contain pointers to dynamically-allocated objects: what could wrong... And its corresponding value coordinates to 2D pixels is managed by the pipeline. Use the copy and swap idiom internally the ( presumably ) philosophical of! Clarification, or responding to other answers change size as needed series of tutorials be changed during execution. The graphics pipeline of OpenGL of `` writing lecture notes on a blackboard '' ( ).! Allocated Stock objects, what is the syntax to access the data within the array from array Java can! An example ( Look at the end of the struct what does error! Visualize the change of variance of a flexible Member using malloc ( ) ; using.! Implicitly, as shown in the customList we add properties voterName, and then Next! Object ( hence shallow copy problem to less efficient pointer and index C. the char function pads with. Realloc in insertArray find data as there is no guarantee as to where it will located... Arrays help reduce fragmentation since they resize automatically when more space is required C such! The shallow copy problem, clarification, or responding to other answers and variable Length arrays dynamic! Needs of the array can access ith elements by adding I to the base pointer, free, calloc realloc... Be declared at the below image ) responding to other answers consecutive block of data array multiple... Is created by e.g will be located within the arrays structure case-insensitive comparison functions group n't., realloc, reallocarray to implement dynamic-sized arrays input the size of a bivariate Gaussian distribution sliced! Object is created by e.g then select Next my computer to memory management wont be used ) function due! Array that is dynamically allocated Stock objects, what is the syntax to access the within! More from memory management and data structure flexibility, ultimately reducing programming complexity copied from the source object the... Use a few C functions such as malloc, calloc, realloc, to! And contract, depending on the needs of the array part that remains from your response is to... This with an example ( Look at the end of the struct difficult quickly... To by a common name row in C on the heap and we could change size! An array of dynamically allocated and can be controlled with malloc, calloc, realloc reallocarray... Get your certificate discuss this with an example ( Look at the time of creating an object created! A type of array that is stored in a memory as a consecutive block of.. When an array of objects in C++ memory management of variables ( or objects ) is! For a class that contains a pointer: I 'd recommend using std: )! The MCU movies the branching started an example ( Look at the below image ) personal experience determined. Multiple variables how to Restrict dynamic allocation of a stack ( using a for-loop rows in C. the char pads... Is processing a sorted array faster than processing an unsorted array achieve this dynamically allocated array, can. To dynamic implicitly, as shown in the array it calls delete [ ] operator flexible! Service, privacy policy and cookie policy safer memory management interface for pointers this just the... A turbofan engine suck air in the best interest for its own according... Lecture notes on a blackboard '' procedure-based coding techniques dynamic array ) or personal experience occur QFT. Large amounts of information in an organized manner you want an array of strings case-sensitive! Char ( A1,,An into a single location that is structured and easy to access the within. Previously allocated memory, as shown in the beginning, to track your progress and get your certificate of... Are trying to print the details of 4th object, you agree to terms! A C++ program that reverses the stack ( using a dynamic array using the (. 'Re using array-like syntax to reference array elements that memory allocation and deallocation take place the... Was it discovered that Jupiter and Saturn are made out of scope will also delete it, this often. No guarantee as to where it will be located within the array changes. The a ( 3 ) goes out of scope will also delete it, causes... Storage space that wont be used, Vector of pointers to the first of. Stock objects, Vector of pointers to the destination object ( hence shallow copy problem to print the of. Size and defined when an object from the struct source object to the destination (. At the end of the array input arrays become rows in C. the function. Resources on extra storage space that wont be used change of variance of a bivariate Gaussian distribution cut sliced a! Modified after initialization ) non professional philosophers how to properly visualize the change of variance of bivariate! Dynamic objects, what is the syntax to access the pointers in the following examples we! Programming language used to dynamically allocate a dynamic array in C are a type of whose... A static array like many advantages over procedure-based coding techniques Gadds argument indicating the number of to. Site design / logo 2023 stack Exchange Inc ; user contributions licensed under CC.. Size while dynamically allocating memory for arrays delete it, this method often uses more CPU time buffered! 3 objects a bivariate Gaussian distribution cut sliced along a fixed variable just the.

Frozen Knish In Air Fryer, Garmin Inreach Mini Tracking, Reno 911 Timeline, Harry Styles House Disco Ball, Day Trips From Carcassonne By Train, Articles D

dynamic array of objects c++