POD-types and inheritance in c++11: Why is it not possible to inherit and extend, and still be a POD-type

236 Views Asked by At

I think this is best explained with an example:

    #include <iostream>

struct A
{
    int a;
};
struct B
{
    A a;
    int b;
};
struct C: A
{
    int c;
};

static inline std::ostream& operator<< (std::ostream& os, const A& a)
{ return os << a.a; }
static inline std::ostream& operator<< (std::ostream& os, const B& b)
{ return os << b.a << " " << b.b; }
static inline std::ostream& operator<< (std::ostream& os, const C& c)
{ return os << c.a << " " << c.c; }

static_assert(std::is_pod<B>::value, "B");
static_assert(std::is_pod<A>::value, "A");
static_assert(std::is_trivial<C>::value, "C");
//static_assert(std::is_pod<C>::value, "C");

int main()
{
    std::cout << "sizeof(A) " << sizeof(A) << std::endl;
    std::cout << "sizeof(B) " << sizeof(B) << std::endl;
    std::cout << "sizeof(C) " << sizeof(C) << std::endl;
    B b = B{14,42};
    std::cout << "b " << b << std::endl;
    C c; c.a=15; c.c=43;
    std::cout << "c " << c << std::endl;
    B* bp = &b;
    std::cout << "(C)b " << *(C*)(bp) << std::endl;
    C* cp = &c;
    std::cout << "(B)c " << *(B*)(cp) << std::endl;

    return 0;
}

Output:

sizeof(A) 4
sizeof(B) 8
sizeof(C) 8
b 14 42
c 15 43
(C)b 14 42
(B)c 15 43

Why does C not qualify as standard_layout. As I would expect it has the same memory layout as B. What could potentially differ?

0

There are 0 best solutions below