The offset of a parent in a child.

Dirk Zoller 1164-32@onlinehome.de
Thu Nov 25 11:41:00 GMT 1999


Dear GCC maintainers,

I need to know, where inside a child class the parent is located.
To find this byte offset I use a macro like this:

	#define PARENT_OFFSET(T,P) (unsigned ((P *)((T *)16)) - 16)

(Dear compiler, imagine at 16 there is a Child T, give me the address
of the parent P of that child, take that as an unsigned and subtract
the 16). If I used 0 then the special treatment of NULL-pointers would
break the procedure.

This works with the compilers I use (gcc-2.95.2, MS-Visual-C, SunPRO CC).
It does not work any more with 

	test.cc:19: non-lvalue in unary `&'

I don't see another way to find out this information. I tried to rewrite
the macro using C++-style casts, made variations with casts to references,
but nothing helped.


Another issue is, that such an expression is no more a
const expression for gcc. (It was in gcc-2.8.1 and early egcs'es.)

This forces an initialized struct which holds such offsets into the
writable data segment and trivial initialization code being generated.


FYI: In my application I generate records describing my data in order
to allow very generic programming. The described data is organized
hierarchically using C++ inheritance. The descriptor records are written
as initialized structs. This PARENT_OFFSET() macro call is among the
member initializers. There are plenty of these descriptors. It would
be nice if the expression was a "constant expression" again.

With kind regards

Dirk Zoller

-- 
Dirk Zoller					Phone:  +49-69-24004649
Sol-3 GmbH&Co KG				Fax:    +49-69-24004650
Obere Marktstraße 5				e-mail: duz@sol-3.de
63110 Rodgau
Germany

#define PARENT_OFFSET(T,P) (unsigned ((P *)((T *)16)) - 16)

struct x { int n; };
struct y { int m; };

struct z : public x, public y { int k; };

struct h { unsigned x; };

// These work:

const int o1 = PARENT_OFFSET (z, x);
const int o2 = PARENT_OFFSET (z, y);

// But not these:

const h h1 = { PARENT_OFFSET (z, x) };
const h h2 = { PARENT_OFFSET (z, y) };


More information about the Gcc-bugs mailing list