1

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Seokmin Hong
  • 612
  • 1
  • 5
  • 15
  • 4
    _"I think it works very well"_ What do you mean by that? – Lightness Races in Orbit Jul 14 '17 at 10:28
  • 2
    you are trying to disprove the standard with a single example that appears to "work well" in one particular compiler and running on one particular machine. That wont work. Anyhow I dont understand the question, as the quote merely defines what a standard layout class is but doesnt mention any restrictions – 463035818_is_not_an_ai Jul 14 '17 at 10:29
  • Indeed this is a pretty vacuous question. It's like complaining that someone decided a "car" is defined by having three or four wheels, observing that they can still get to work on a bike. It just makes no sense. – Lightness Races in Orbit Jul 14 '17 at 10:30
  • I meant datas of the structure C lying on the memory in a row. – Seokmin Hong Jul 14 '17 at 10:31
  • "It behaves how I expected it to" is *a possible* outcome from undefined behaviour. The standard makes *no* guarantees about the behaviour staying that way. – Caleth Jul 14 '17 at 11:22

1 Answers1

8

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055