1

I have class named Novel. I can declare array of objects as mentioned below:

Novel obj;

but problem is Novel has constructor which I want to be called for all indexes of array how can I do that. I tried following but it does not work.

Novel obj(i,n)[2];
1
  • Basically, you can't. Commented Apr 25, 2014 at 10:47

2 Answers 2

4

You need to use a proper container that uses dynamic allocation to defer construction of individual elements.

std::vector<Novel> objs(2, Novel(i,n));
Sign up to request clarification or add additional context in comments.

Comments

0

Unfortunately the C++ language does not provide that capability. Arrays are allocated, but by default they are not initialised at all. If they are allocated in static storage they get filled with zeros; you can give a brace-initialiser; and you can provide a default constructor to initialise each value. What you cannot do is initialise an array with any other constructor.

To achieve a similar effect you have to approach the problem from a different angle. Basically, you can: - write a macro or template that both allocates an array and calls a constructor on each element under the covers, or - create an object with array semantics, which can initialise itself any way you like.

The built in collection classes are usually the best solution. For example, std::vector provides fill, range and copy constructors as well as array semantics. One of the other answers provides an example, but there are several ways to do it.

std::vector<Novel> objs(2, Novel(i,n));

It's not an array, but it should do what you need.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.