Reputation: 1707
I have defined an array within a class. I want to initialize the array with some values pre-decided value. If I could do it in definition only then it will be easier as I would have used
class A{
int array[7]={2,3,4,1,6,5,4};
}
But, I can't do that. This, I need to do inside Constructor. But I can't use the same above syntax as it would create a new array inside Constructor and won't affect the array defined in class. What can be the easiest way to do it?
class A{
public:
int array[7];
A::A(){
}
}
Upvotes: 2
Views: 12594
Reputation: 1
You can initialize the array in the constructor member initializer list
A::A() : array{2,3,4,1,6,5,4} {
}
or for older syntax
A::A() : array({2,3,4,1,6,5,4}) {
}
Your sample should compile, using a compiler supporting the latest standard though.
Also note your class declaration is missing a trailing semicolon
class A{
public:
int array[7];
A();
};
// ^
Upvotes: 7
Reputation: 447
With C++11 you can write this:
class C
{
int x[4];
public:
C() : x{0,1,2,3}
{
// Ctor
}
};
Upvotes: 1