c++arraysstringclass

Define and instantiate C style array of string inside class


I am trying to create a class with an array of string defined inside. I want this array of string to be defined when the class is instantiated.

Here is my attempt below (or the code showing my intentions).

class a_class
{
  public:
    static char const *arr_str[];
    int idx;
    void a_function();
  private:
};

a_class MyClass({"aaa", "bbb", "ccc"}, 3);

Obviously the above code does not compile well at all.

How can I achieve this?


Solution

  • Your array is static, so it is not tied to any specific instance of a_class. You should not be using an instance constructor to initialize it. In modern C++, you can initialize a static class member right in its declaration.

    Also, your class does not explicitly define a non-default constructor (ie a constructor that requires arguments be passed in), as such you can't use parenthesis when constructing a new instance of the class while passing in argument values, as your example is doing. The compile will fail with an error about a matching constructor not being found. So, you will have to use curly-braces instead to initialize the non-static member directly.

    Try this:

    class a_class
    {
      public:
        static constexpr char const *arr_str[] = {"aaa", "bbb", "ccc"};
        int idx;
        void a_function();
      private:
    };
    
    a_class MyClass{3};
    

    Live Demo

    On the other hand, if you want a per-instance array, then it should not be a static member, eg:

    template<size_t N>
    class a_class
    {
      public:
        char const* arr_str[N];
        int idx;
        void a_function();
      private:
    };
    
    template<size_t N>
    a_class(char const * (&&)[N], int) -> a_class<N>;
    
    a_class MyClass{{"aaa", "bbb", "ccc"}, 3};
    

    Live Demo

    Alternatively, use a dynamic-sized std::vector instead of a fixed-sized array, eg:

    #include <vector>
    
    class a_class
    {
      public:
        std::vector<char const*> arr_str;
        int idx;
        void a_function();
      private:
    };
    
    a_class MyClass{{"aaa", "bbb", "ccc"}, 3};
    

    Live Demo