Search code examples
c++inheritancebase-classobject-address

Guarantees on address of baseclass in C++?


In C struct's, I'm guaranteed that:

struct Foo { ... };
struct Bar {
  Foo foo;
  ...
}
Bar bar;
assert(&bar == &(bar.foo));

Now, in C++, if I have:

class Foo { ... };
class Bar: public Foo, public Other crap ... {
  ...
}

Bar bar;
assert(&bar == (Foo*) (&bar)); // is this guaranteed?

If so, can you give me a reference (like "The C++ Programming Language, page xyz")?

Thanks!


Solution

  • There is no guarantee. From the C++03 standard (10/3, class.derived):

    The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified.