Search code examples
c++unionsstatic-initializationstatic-initializer

Static initializing a struct of unions of arrays


I am trying to write static initializers for this class:

class Cube3x3
{
    union CornerData
    {
        u8  mData8[8];
        u32 mData16[4];
        u32 mData32[2];
        u64 mData64;
    };

    union EdgeData
    {
        u8  mData8[12];
        u32 mData32[3];
    };

    CornerData mCorners;
    EdgeData mEdges;

    static const Cube3x3 sSolved;
};

I've tried this, and a lot of variants, and it seems like nothing I try will work.

const Cube3x3 Cube3x3::sSolved =
{
    { 0, 0, 1, 0, 0, 0, 1, 0 },
    { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }
};

Does anyone know how, or if, its possible to static initialize this?


Solution

  • If you are willing to change Cube3x3 from a class to a struct, you can use:

    const Cube3x3 Cube3x3::sSolved = {0};
    

    Update

    When a struct is used, you can also initialize the members with non-zero values, like you have in the updated question.

    const Cube3x3 Cube3x3::sSolved =
    {
        { 0, 0, 1, 0, 0, 0, 1, 0 },
        { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }
    };