Re: Inheritance and offsetof
On Sep 22, 11:05 pm, "Francesco S. Carta" <entul...@gmail.com> wrote:
On 22 Set, 23:03, James Kanze <james.ka...@gmail.com> wrote:
[...]
No. The only thing a C-style cast can do that static_cast
or reinterpret_cast (combined with const_cast) can't is cast
to a private base class.
Uh... black magic... but, wait: GCC 3.4.5 allows me
reinterpret_cast- ing a derived class to all of its base
classes, even to private ones... is that a bug?
No. But it's not doing what you think---reinterpret_cast
doesn't cast up and down in a hierarchy; it tells the compiler
that the actual pointer you have points to some different type.
To get an idea of what I mean, try the following:
#include <iostream>
struct A { int a ; } ;
struct B { int b ; } ;
struct C : A, B { int c ; } ;
int
main()
{
C obj ;
obj.a = 1 ;
obj.b = 2 ;
obj.c = 3 ;
C* pc = &obj ;
B* pb1 = static_cast< B* >( pc ) ;
B* pb2 = reinterpret_cast< B* >( pc ) ;
std::cout << "using static_cast: " << pb1 << " (" << pb1->b <<
")\n" ;
std::cout << "using reinterpret_cast: " << pb2 << " (" << pb2-
b << ")\n" ;
}
At least on my system, seems that I really don't need C-style
casts at all, I think I won't upgrade it very soon ;-)
You generally don't need C-style casts. Or reinterpret_cast
either, for that matter.
--
James Kanze