Reputation: 622
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.
Then, why is there the restriction for having non-static members in the inherited standard-layout rules?
Upvotes: 1
Views: 110
Reputation: 385274
Keep reading:
Standard-layout classes are useful for communicating with code written in other programming languages.
The rule you cited requiresthat only one class in the object's inheritance heirarchy consists of data. Consequently, such a type is "easy" to use for communicating with code written in other programming languages which may implement inheritance very differently (or, like C, not at all).
The rule doesn't mean you can't have more complicated types, or that you can't use those types in various exotic and interesting ways; it just means that they won't be specifically called "standard layout" types, with the consequences that go along with not being in that category of type.
Upvotes: 8