-1

In order to create an array of ints dynamically, I need to do int *a = new int[20];.

Is there a similar way to create an array of objects or structs?

For example, I need a dynamically allocated array of objects of class A, how should I declare it(Syntax)?

What constructor would be called on each object(if at all any constructor is called)?

4
  • 1
    You could A* a = new A[20];, and the default ctor will be called. Commented Apr 20, 2016 at 5:24
  • 1
    Could I recommend std::vector instead of new expression? Commented Apr 20, 2016 at 5:25
  • @NickyC I want to understand how that would work. I know I can use std::vector. But How does it actually work? Commented Apr 20, 2016 at 5:27
  • 2
    This is already answered here: http://stackoverflow.com/questions/8462895/how-to-dynamically-declare-an-array- ​of-objects-with-a-constructor-in-c Google is your friend. Commented Apr 20, 2016 at 5:32

3 Answers 3

2

Using arrays with pointer:

A* a = new A [20];

Without pointers

A a [20];

I suggest to use vectors:

//init
std::vector<A> aList;

//reserve memory size - not necessary 
aList.reserve (20);

 //put elements in
 aList.push_back (A ());

 //access elements
 aList [0];
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it using this line:

A* a = new A[N];

How it works?

the new keyword will allocate N sequential block in the heap. Each block has a size of sizeof(A) so the total size in bytes is N*sizeof(A). Allocating those objects in memory is ensured done by calling the default constructor N times.

Alternative:

Use std::vector instead. It will do all the work for you.

Comments

1

Syntax(c++):

ClassName *classObject = new ClassName;

For example, Let's assume a class called car.

car *obj = new car;    

car *obj = new car[n];  // n objects will be created by calling the def. constructor

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.