vendredi 14 juillet 2017

Why is there a rule for having non-static members in the inherited standard-layout rules?

I read a very nice article about POD, Trivial, Standard-layout classes. But I have a question for standard-layout classes' rule:

either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members

I wrote a source code:

#include <iostream>

struct A {
    int a;
};

struct B {
    int b;
};

struct C : A, B {
    int c;
};

int main() {
    C c = {}; // initialize C
    c.a = 0xffffffff;
    c.b = 0xeeeeeeee;
    c.c = 0xdddddddd;
    std::cout << std::hex << *(reinterpret_cast<int*>(&c)  ) << std::endl;
    std::cout << std::hex << *(reinterpret_cast<int*>(&c)+1) << std::endl;
    std::cout << std::hex << *(reinterpret_cast<int*>(&c)+2) << std::endl;
}

The result is:

ffffffff
eeeeeeee
dddddddd

I think it works very well. And using debugger in VS2015, it looks fine.

enter image description here

Then, why is there the restriction for having non-static members in the inherited standard-layout rules?

Aucun commentaire:

Enregistrer un commentaire