Array with Strings in class

I'm trying to make use of an array inside a class but I get stuck.
The array should become an array of strings.

class myTest{
  private:
    String myArr[]; 
  public:
  
  };

String myTest::myArr = {"first element","second element"};


I get the following errors at compilation time:

sketch_dec16a:3:18: error: flexible array member 'myTest::myArr' in an otherwise empty 'class myTest'
String myArr[];
^
sketch_dec16a:8:16: error: 'String myTest::myArr' is not a static data member of 'class myTest'
String myTest::myArr = {"first element","second element"};
^~~~~
sketch_dec16a:8:57: error: conversion from '' to 'String' is ambiguous
String myTest::myArr = {"first element","second element"};
^

flexible array member 'myTest::myArr' in an otherwise empty 'class myTest'

You must specify the array size when it's inside a class or struct.

If I do so then I get other errors

class myTest{
  private:
    String myArr[2]; 
  public:
  
  };

String myTest::myArr = {"first element","second element"};

Errors:
sketch_dec16a:8:16: error: 'String myTest::myArr' is not a static data member of 'class myTest'
String myTest::myArr = {"first element","second element"};
^~~~~
sketch_dec16a:8:57: error: conversion from '' to 'String' is ambiguous
String myTest::myArr = {"first element","second element"};
^
'String myTest::myArr' is not a static data member of 'class myTest'

The initial value needs to go in the class definition:

class myTest {
  private:
    String myArr[2] = {"first element", "second element"};
  public:
};

Or in the class constructor:

class myTest
{
    String myArr[2];

  public:
    myTest();

    void print(int n)
    {
      Serial.println(myArr[n]);
    }
};

myTest::myTest() : 
  myArr({"first element", "second element"}) 
{}

void setup()
{
  myTest test;

  Serial.begin(115200);
  delay(200);
  test.print(0);
  test.print(1);
}

void loop() {}

Thanks that solves the problem.
I'm not familiar with the code though.
The colon after the function constructor is new to me.

myTest::myTest() : 
  myArr({"first element", "second element"}) 
{}

I
C++ initialiser list

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.