Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a member array of class in the constructor?

Tags:

c++

I am trying to do the following:

class sig
{
public:

int p_list[4];
}

sig :: sig()
{
p_list[4] = {A, B, C, D};
}

I get an error

missing expression in the constructor.

So how do I initilalise an array?

like image 464
chintan s Avatar asked Jul 23 '12 10:07

chintan s


People also ask

Can we initialize array in constructor?

You can initialize the array variable which is declared inside the class just like any other value, either using constructor or, using the setter method.

How do you initialize an array of classes?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

How do you initialize a constructor class?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.


1 Answers

In C++11 only:

class sig
{
    int p_list[4];
    sig() : p_list { 1, 2, 3, 4 }   {   }
};

Pre-11 it was not possible to initialize arrays other than automatic and static ones at block scope or static ones at namespace scope.

like image 133
Kerrek SB Avatar answered Nov 15 '22 22:11

Kerrek SB