0

I never had to approach this before, but can you pass arguments to C++ contructors when creating an array off or on the heap. I have the same question for java, can you pass arguments to contructors when creating an array of objects, or must you just use the default contructor for both C++ and Java.

Thanks :-)

1
  • 2
    For C++, do you mean array or vector? std::vector<> should be used in most cases where somebody might use an array. Commented Apr 5, 2011 at 19:43

6 Answers 6

3

You already got a few Java answers, but in C++, when you create an array with automatic storage duration (I guess what's what you mean by "off the heap"), you can pass arguments to the constructors of each element:

std::string array[] = {"foo", "bar", "baz"};

or, if there is no implicit conversion

std::complex<double> another[] = { std::complex<double>(1.0,  1.1),
                                   std::complex<double>(3.0, -1.1) };

But this is not possible when the array is created with new[]. However, std::vector is the standard C++ approach for dynamic arrays, which of course allows this:

std::vector<std::string> vector(100, "foo"); // 100 elements, each set to "foo"
Sign up to request clarification or add additional context in comments.

7 Comments

what I meant for c++ is something along the lines of: ObjectType* object = new ObjectType(Constructor Arugments)[numberof Arguments];
@rubixibuc : you could implement such form of new[] (it might use std::uninitialized_fill internally), but the result would be essentially a re-implementation of a part of std::vector.
@Cubbi, it gives me an error when I try compile something similiar to that, what would be the approriate way to initialize and array of user created objects in C++.
@rubixibuc : you get an error because the syntax is slightly different. Remember to NEVER use this in real life: ideone.com/mQedX . As already mentioned, std::vector is the correct way to allocate arrays dynamically in C++.
@Cubbi, @rubixibuc: That piece of code is wrong. The contract of new requires it to allocate memory, not initialize. That code will break very badly with objects that have non-trivial constructors, as every object in the array will be constructed twice, first in the new and then with the default constructor, which means that in many cases it will leak memory. If I could downvote the comment I would, I am even considering marking it as offensive!!! :)
|
1

Java:

String [] as = new String [] {new String ("foo"), new String ("bar")};

This is just initialization of the array with elements while declaring it.

But your question shows a misconception: 'or must you just use the default constructor for creating an array of objects'.

You often declare an array in Java without declaring the elements in the array. You thereby define the size of the array and the types it will contain - however there is no difference between standard-ctor or not.

There is only a difference between embedded types and Objects. If you define an array of embedded types (int, char, boolean, double, ... - sometimes called 'primitive') they get initialized to their default value (0, 0.0 or false).

int [] ia; // only declares the array as of type int
int [] ia = new int [4]; // +size =4, all elements are 0
int [] ia = new int [] {3, 4, 5}; /* elements defined, and 
  size is implicitly set to 3 */
String [] sa; // only declared, type defined
String [] sa = new String [4]; /* type and size defined
  but no elements, no strings defined */
String [] sa = new String [] {new String ("exit")}; /* type defined, size implicitly (1), one element= String defined, using a constructor */

But for a class with a default constructor, which is a constructor which takes no arguments, doesn't get automatically created:

String [] sa = new String [4]; /* no String defined so far,
  although there is a standard-CTOR for String */

It is in perfect analogy to simple elements. If you have a class:

class Foo {
    int a; 
    File file; 
    String s; 
}

a is initialized to 0 as a primitive type, but file and s are null, regardless whether there is a standard constructor (for s, there is, for file, there isn't).

Comments

0

In java when you create an array of objects, you are only creating references variables.

JButton[] buttonArray = new JButton[10]; // Creates 10 references
buttonArray[0] = new JButton("MyButton"); // here's where the constructor is called.

3 Comments

depends on how you do it: JButton [] ajb = new JButton [] {new JButton ("foo"), new JButton ("bar")};
it's just a short form for the above but technically identical.
I don't think that it is correct to say 'you are only creating reference variables' (your line 1). But the question or must you just use the default contructor for creating an array of objects implies more of an misunderstand. You often declare an array in Java without declaring the elements in the array. You thereby define the size of the array and the types it will contain - however there is no difference between standard-ctor or not. It's only a differnce between embedded types and Objects.
0

In Java when you do something like:

x = new Object[100];

you get spaces for 100 Objects and they all point to null.

You need to loop over it like:

for(int i = 0; i < x.length; i++)
{
    x[i] = new Object();
}

2 Comments

Object just has an default contructor, so of course you can't show a non-default constructor at work, together with Object. Except for derived classes, like String, shown in my example.
Umm... the constructor isn't called in the new which was my point... new <class> isn't called when you make the new array. When creating an array of objects (and not initializing them at the same time) you cannot call any constructor.
0

When you create an array they're all null (unless they're primitives then they're the default value, which is 0 for number primitives, and false for booleans.)

Since no objects are made, there's no constructor to pass arguments into, until you iterate over the array and make your objects, that is.

1 Comment

booleans are false by default too.
0

I just wanted to post this. The first statemment will throw an error the second won't. In another response it said you could use implicit conversion (@Cubbi thank you for showing me that :-)). I just thought this code might help anyone that get's stuck on this, and want to test what error message you get. The first one causes an compile error becuase there is no default constructor, the second one doesn't because it uses implicit conversion.

#include <iostream>

using namespace std;

class NoArray
{
    public:
        NoArray(int a) : b(a)
        {
            cout << a << endl;
            cout << b << endl;
        }
    int b;
};

int main()
{
    //NoArray d[10]; This will throw and error
    NoArray e[] = {1,2,3,4}; // This won't
}

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.