Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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{};

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

namespace B{
const extern B array[24];
}

cpp:
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)};
}

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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() {} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading