Init an array in a class

V

Vij

I can do this
int a [] = { 5,6,7,8,9};

but how can I do this inside a class? something like this

class CTest
{
private:
int a [] // Init the array here
};
 
G

Gabriel

Vij said:
I can do this
int a [] = { 5,6,7,8,9};

but how can I do this inside a class? something like this

class CTest
{
private:
int a [] // Init the array here
};
I would do it like this:
// header file
#include <vector>
class CTest
{
public:
CTest();
private:
std::vector<int> a;
}

//source file
namespace{
// solution 1 for short arrays:
std::vector<int> init_a()
{
std::vector<int> result(5);
a.at(0) = 5;
//...
a.at(4) = 9;
return result;
}

// solution 2 for long array:
std::vector<int> init_a()
{
const int a [] = {5, 6, 7, 8, 9};
return std::vector<int>(a, &a[5]); // You might have been looking for
this? vector constructor can take two iterators.
// or, to be very safe:
// return std::vector<int>(a, &a[sizeof(a) / sizeof(int) - 1]);
}

} // unnamed namespace

CTest()
: a(init_a())
{}

- Gabriel
 
M

Manvel Avetisian

I can do this
int a [] = { 5,6,7,8,9};
but how can I do this inside a class? something like this
class CTest
{
private:
int a [] // Init the array here
};

You can't specify explicit initializers for arrays in constructor's
initialization list nor in class declration. You can initialize array as
described before or use static arrays:

struct A
{
static int a[];
};

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

void main() {
A x;
}
 
R

Rolf Magnus

Vij said:
I can do this
int a [] = { 5,6,7,8,9};

but how can I do this inside a class?

You can't.
something like this

class CTest
{
private:
int a [] // Init the array here
};

An array needs a size. In the first example, the size can be deduced from
the initializer. But in a class, you can't put an initializer here, so you
must specify a size. Further, non-static array members cannot be
initialized at all in C++.
So the only thing you can do is explicitly specify a size for the array and
assign all the elements in the constructor, like:

class CTest
{
public:
CTest()
{
a[0] = 5;
a[1] = 6;
a[2] = 7;
a[3] = 8;
a[4] = 9;
private:
int a [5];
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top