12

suggest we have an array of class A's objects, and class A's constructor require two arguments, like this:

class A  
{  
public:  
    A( int i, int j ) {}  
};  

int main()  
{
    const A a[3] = { /*How to initialize*/ };

    return 0;
}

How to initialize that array?

0

4 Answers 4

12

Say:

const A a[3] = { {0,0}, {1,1}, {2,2} };

On older compilers, and assuming A has an accessible copy constructor, you have to say:

const A a[3] = { A(0,0), A(1,1), A(2,2) };

C++ used to be pretty deficient with respect to arrays (certain initializations just were not possible at all), and this got a little better in C++11.

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

3 Comments

In the first case, the compiler just issue a warming: 'main.cpp:10:32: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default].' What does "accessible" mean? a public one?, and, thank you.
@UniMouS: On GCC, compile with -std=c++0x. Accessible means that you can access it, i.e. it's not private or =deleted.
thank you, @Kerrek: and what's the meaning of =delete ?
1

As long as the type has a copy constructior (whether synthesized or explicitly defined) the following works:

A array[] = { A(1, 3), A(3, 4), A(5, 6) };

This work both with C++2003 and C++ 2011. The solution posted by KerrekSB certainly does not work with C++ 2003 but may work withC++ 2011 (I'm not sure if it works there).

1 Comment

The copy constructor also needs to be accessible. Just having one isn't enough.
0

you can provide a default constructor and initialize your array as normal. After successful initialization, use a loop to reassign values to each member

Comments

0

i think it should be like this

const A a[3] = { A(1, 2), A(3, 4), A(5, 6) };

2 Comments

the new will make you pointers-to-A, not A-instances
the compiler issue an error: main.cpp:9:42: error: conversion from ‘A*’ to non-scalar type ‘A’ requested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.