Search code examples
c++structsizeof

How to get sizeof not yet defined struct in C++


struct S1
{
    size_t v = sizeof(S2); //compiler error here
};

struct S2
{
    S1 s1;
};

the struct S2 needs to be below S1 so it can have it as a member, but I also want the sizeof(S2) to be stored in S1.

I made a workaround where I put a function prototype that returns the sizeof(S2) but is defined after S2 is defined, like so:

size_t func();

struct S1
{
    size_t v = func();
};

struct S2
{
    S1 s1;
};

size_t func()
{
    return sizeof(S2);
}

But I feel like this is a really ugly and bad solution, is there a better way?


Solution

  • When you use a constructor rather than the in class initializer the issue is gone:

    struct S1
    {
        size_t v;
        S1();
    };
    
    struct S2
    {
        S1 s1;
    };
    
    S1::S1() : v(sizeof(S2)) {}