Topic: inheritance and memory layout question


Author: David R Tribble <david.tribble@central.beasys.com>
Date: 1997/03/06
Raw View
cano@loc201.tandem.com (cano_jonathan) wrote:
> given:
>
> class base {    // a POD class
>     int a;
> };
>
> class derived : public base {   //  a POD class
>     char c;
> };
>
> class composed {        // a POD class
>     base  b;
>     char  c;
> };
>
> Will the memory layout of `derived' objects be the same as the memory
> layout of `composed' objects, assuming all the classes above are POD
> classes?  How about if only `base' is a POD class?

No guarantees are made about member order for derived classes.  Member
derived::c may follow, or come before, member derived::a.
On HP-UX, for instance, base class members follow derived class members
in memory.  I'm sure it's the opposite on other implementations.

You are guaranteed that within the groups of public, protected, and private
members that member variables will occur in the order specified.  For
example:

    class Foo
    {
    public:
        int     a, b, c;
    protected:
        int     i, j, k;
    private:
        int     x, y, z;
    };

These statements are guaranteed true for class Foo:
    1) &a < &b < &c.
    2) &i < &j < &k.
    3) &x < &y < &z.

No other guarantees are made (such as &a < &i or &a > &i).  These rules
are what allow POD types (with all-public members) to work like good old
C structs.
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]