4

Is there a way in C++ where an objects has argument added upon it, with an array such as:

int x = 1;
int y = 2;

Object myObject( x, y )[5]; // does not work

I was hoping that I could put arguments into the object, while creating an array of 5 of these objects, does anyone know how? and is there a bteter way?

1
  • 1
    -1: No language specified. Could be Java. Not clear, however. Commented Apr 22, 2009 at 23:27

4 Answers 4

7

When constructing an array of objects in C++ only the default constructor can be used unless you're using the explicit Array initialization syntax:

Object myObject[5] = { Object( x, y ),
                       Object( x, y ),
                       Object( x, y ), 
                       Object( x, y ), 
                       Object( x, y ) }

Here's some good information from the C++ FAQ about this:

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.5

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't mind using a vector instead of an array:

std::vector<Object> obj_vec(5, Object(x, y));

Or if you really want an array and don't mind initializing it in 2 steps:

Object obj_array[5];
std::fill_n(obj_array, 5, Object(x, y));

2 Comments

I don't get this part. You need to have a default constructor with no arguments for first line to be true. Then, you fill that memory location with dynamically created objects. Then why don't we use pointers instead of real objects. They are basically useless here.
@Halil Kaskavalci: I don't understand your comment. Do you refer to the suggestion to use the vector ctor or to the one using fill?
0

Or something like this:

int x = 1;
int y = 2;
int numObjects = 5;

Object myObjectArray[numObjects];

for (int i=0, i<numObjects, i++) {
    myObjectArray[i] = new myObject(x,y);
}

Maybe it's a function with x,y and numObjects as params?

Comments

0

You haven't mentioned which language yet, but in C# 3.0 you can get close with collection initializers:

var myObject = new List<Object>() {
    new Object(x,y),
    new Object(x,y),
    new Object(x,y),
    new Object(x,y),
    new Object(x,y)
};

2 Comments

You should have mentioned that you submitted this before a language was specified.
It's not too late -- look again ;)

Your Answer

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