By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,493 Members | 1,289 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,493 IT Pros & Developers. It's quick & easy.

Init an array in a class

P: n/a
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
};

Sep 6 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Vij wrote:
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
Sep 6 '05 #2

P: n/a
On Tue, 06 Sep 2005 15:30:24 +0400, Vij <vi******@gmail.com> wrote:
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;
}
Sep 6 '05 #3

P: n/a
Vij wrote:
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];
};

Sep 6 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.