Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly Bracket Initialization in C++ and Java

Tags:

java

c++

arrays

In the code below, I don't seem to understand the limitations of the curly bracket initialisation. What do they actually do? It seems in the case of A it just sets a[0] equal to the value directly. In the case of b it using implicit conversion. Does it decide which one to do based on what is available, or is there some other method it uses?

#include <iostream>

using namespace std;

struct A
{

};

struct B
{
    B(int a) { cout << a; }
};

int main()
{
    A* a[] = {new A()};
    B b[] = {1};    
}

Also would this type of curly bracket initialisation work similarly in Java?

public class A
{
     public static void main(String[] args)
     {
          someClass[] sC = { /* what can go here? an argument to the constructor,
                               or just a value to set the variable equal to */ }.
     }
}

Sorry if my question seems silly, just really want to know more about curly brackets in c++ and Java. Thanks in advance :-)

like image 571
rubixibuc Avatar asked Jan 18 '23 14:01

rubixibuc


2 Answers

Since the Java part has already been answered, I will add a bit about the C++ part. The specific version of curly brace initialization that you refer to is called aggregate initialization and (unsurprisingly) is used to initialize aggregates. Each element in the aggregate will be initialized with the corresponding element inside the braces and you can use whatever you want to use that can be implicitly convertible to the type of the element in the aggregate.

There are a couple of specific parts of the feature that you might want to consider for the specific case of arrays. The number of elements inside the curly braces cannot be greater than the size of the array, but it can be smaller in which case the rest of the elements will be default initialized.

int a[5] = { 1, 2 }; // [ 1, 2, 0, 0, 0 ]

If the size of the array is not provided in user code, the compiler will set it to the number of elements in the aggregate-initialization list:

int a[] = { 1, 2, 3 }; // int a[3]

Note that unlike in Java, the size is an integral part of the type of the array, so that while you can type int a[] = { 1 };, it can never be a generic array of undetermined number of int.

In C++11 the curly brace syntax has been extended to provide uniform initialization, but that is probably outside of the scope of the question, I just mention it in case you want to read more on the subject.

like image 79
David Rodríguez - dribeas Avatar answered Jan 21 '23 05:01

David Rodríguez - dribeas


It's the same thing as in C++

someClass[] sC = { new someClass(), new someClass(), new someClass() };
int[] i = { 1, 2, 3 };
String[] s = { "1", "2", "3" };
like image 36
Jon Lin Avatar answered Jan 21 '23 03:01

Jon Lin