0

I want to have an array as a class member, but the only way I know how to initialize the array in the constructor is by adding each element individually (array[x] = char)

class MyClass
{
  public:
    MyClass();
    ~MyClass();
    void PrintLetters(); // Prints each character in the array
  private:
    int alpha[3]; // Allocate memory for array
};

MyClass::MyClass()
{
    // Initialize the array
    alpha[0] = 1;
    alpha[1] = 2;
    alpha[2] = 3;

    PrintLetters();
}

MyClass::~MyClass()
{
}

void MyClass::PrintLetters()
{
    for (int x = 0; x < 3; x += 1)
    {
        cout << alpha[x] << endl;
    }
}

int main()
{
    MyClass abc;

    return 0;
}  

Is there another way to do it? If I try to do it like this:

MyClass::MyClass()
{
    // Initialize the array
    alpha[3] = {1, 2, 3};

    PrintLetters();
} 

I get the following error: Expression syntax in turbo c++

Parveez Ahmed
  • 1,325
  • 4
  • 17
  • 28

1 Answers1

4

I believe in GCC at least, with -std=c++11, you can do this:

MyClass::MyClass() : alpha{1, 2, 3}
{
    PrintLetters();
}

This is just an array initialization in the member initialization list. It's a standard C++ feature, but some compilers (cough VC++ cough) might not have implemented it yet.

Sam Estep
  • 12,974
  • 2
  • 37
  • 75