Monday, February 22, 2010

How to Initialize an Array in the C++ class

There are various ways in which you can initialize you array in the class
*************************************************************************
Method 1
*************
class A
{
int a[2];

public:
A();

};
A::A()
{
a[0]=1;
a[1]=2;
}
*************************************************************************************
You can also declare a static array and initilazes it's value outside the class scope

Method 2
*************

class A
{
static int a[2];
static const int arr[2];

public:
A(){}

};

int A::a[2] = {0, 1};
const int A::arr[2]={1,2};
*************************************************************************************
Note:

If you want to declare any const array in you class so you have to make it static const because const variables and arrays should be initialized at the time of declaring it.As we know that we cannot initialize arrays in initialization list so we cannot do it so we have to make the array static.

No comments:

Post a Comment