Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 408
anon Avatar asked Jan 31 '10 06:01

anon


1 Answers

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.

like image 116
James McNellis Avatar answered Sep 28 '22 21:09

James McNellis