3

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(){

    }
}
10
  • Use a pointer or predefined array in the class definition or make it static. In the first case you have to fill every entry as a single line. Commented Aug 25, 2014 at 14:14
  • @a_guest Neither of those is a solution to the actual problem at hand. Commented Aug 25, 2014 at 14:16
  • 2
    Your first example is absolutely valid C++11. I just compiled it with Clang. Commented Aug 25, 2014 at 14:16
  • 1
    What @JamesMcLaughlin said. You just have to add a ; to the end of your class definition. Commented Aug 25, 2014 at 14:20
  • 1
    @user3747190: According to this, you'll need at least version 4.7 to support in-class initialisation. My advice is to upgrade if possible; if can't for some reason, you should be able to use list-initialisation in the constructor (as some answers suggest), as long as you enable (partial) C++11 support with -std=c++0x. Commented Aug 25, 2014 at 14:41

2 Answers 2

8

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();
  };
// ^ 
Sign up to request clarification or add additional context in comments.

4 Comments

That requires C++11, in which case OP's code is OK (bar the missing training ;)
I haven't added in question but actually I have many such arrays. So above solution will look a little clumsy.
@user3747190 As mentioned your sample should compile with -std=c++11 and the missing semicolon fixed.
@Vladp There is less than a minute's difference between your posting times, so for most practical purposes, you posted simultaneously. In addition, this answer goes to greater depth and is probably more helpful, since it mentions the OP's other error (trailing semi-colon) as well. But regardless, I would expect a few upvotes to trickle your way eventually.
1

With C++11 you can write this:

class C
{
    int x[4];
public:
    C() : x{0,1,2,3}
    {
        // Ctor
    }
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.