Path: utzoo!attcan!uunet!cs.utexas.edu!wuarchive!decwrl!wsl.dec.com!haynes From: haynes@wsl.dec.com (Charles Haynes) Newsgroups: comp.lang.c++ Subject: Re: calculate member byte offset Message-ID: <1908@bacchus.dec.com> Date: 8 Oct 89 13:10:00 GMT References: <6590284@hplsla.HP.COM> <1989Oct5.193826.24178@polyslo.CalPoly.EDU> Sender: news@decwrl.dec.com Reply-To: haynes@wsl.dec.com (Charles Haynes) Organization: DEC Western Software Lab Lines: 42 The (relatively gross) hack we used in the X Intrinsics is: #define XtOffset(type,field) ((unsigned int)&(((type)NULL)->field)) This has a different set of problems from your example, but works on most architectures/compilers. Some "C"'s provide an offset builtin that you could use. As for the problems with your example: > class foo > { > public: > int grr; > int header; //does header stuff really need to be public? > void alloc(); > }; > > void foo::alloc() > { > cout << (&(this->header)) - this << "\n"; // bomb! 2.0 complains > // that this is of type foo*, while &(this->header) is of type int*. > // Maybe you can get away with coercing them both to type char*, but > // not guaranteed to work with all compilers That's right! You are subtracting things of different type. *I* wouldn't expect it to work in general. This is where I'd use the XtOffset macro. > } > > main() > { > ((foo*) 0) -> alloc(); // bomb? -- possible on a machine that > // disallows dereferencing a null pointer This should be possible on ANY machine. You aren't actually dereferencing anything, you're just selecting a member function and passsing "this" to it. "alloc" had better be ready to get a NULL "this" though. > } Hope this is helpful. -- Charles