Search code examples
c++arraysinitializationprivateclass-constants

How to initialize private static constant array of the same class C++


I need to make class B to work with graph of related objects of class A. An instance of B contains A by value, and links to linked B objects(array indexes). Array of B must to be private as OOP principles dictate. I have long generated initialization list.

//What I want to do(not working)
header:
class A{};

class B{
    static const B array[24]={B(A(),0,0,0,0,0,0),//zeros are numbers
                            ...............//many rows
                            B(A(),0,0,0,0,0,0)};
    A a;
    char l[6];
public:
    B(A _a,char l1, char l2, char l3,char l4, char l5, char l6);
};
//attempt with initialization in cpp
header:
class A{};

class B{
    static const extern B array[24];
    A a;
    char l[6];
public:
    B(A _a,char l1, char l2, char l3,char l4, char l5, char l6);
};

cpp:
static const B::array={B(A(),0,0,0,0,0,0),//zeros are numbers
                       ...............//many rows
                       B(A(),0,0,0,0,0,0)};

I tried above and similar variants. Compiler says I can't use conflicting specifiers or incomplete types or that field was private. In the past instead of class I used namespace and it worked, but that way array is not encapsulated.

//global variable in namespace(works, but not private)
header:
class A{};

namespace NSB{
class B{
    A a;
    char l[6];
public:
    B(A _a,char l1, char l2, char l3,char l4, char l5, char l6);
};
const extern B array[24];
}

cpp:
const NSB array[24]={B(A(),0,0,0,0,0,0),//zeros are numbers
                    ...............//many rows
                    B(A(),0,0,0,0,0,0)};
}

I expect a way to make preinitialized private static array somehow.


Solution

  • Unsure what you tried differently ... that seems to compile (and run):

    class A{};
    
    class B{
        static const B array[2];
        A a;
        char l[6];
    public:
        B(A _a,char l1, char l2, char l3,char l4, char l5, char l6) {}
    };
    
    const B B::array[2]={B(A(),0,0,0,0,0,0), B(A(),0,0,0,0,0,0)};
    
    int main() {}