Re: Common base class, reinterpret_cast, and aliasing
guillaume.melquiond@gmail.com wrote:
Hi,
In the following code, I have an object of type A, and I reinterpret
it as an object of type B (two consecutive static_casts would work
too). Both types share the same ancestor. As the only accesses to
memory are performed through the base::value member, it seems to me
that aliasing rules are not broken: the program will return 42
according to the C++ standard. Is it a correct assumption? If not, is
there a way to achieve this behavior? Thanks.
Your assumption is incorrect. By using the casts, you are forcing
the compiler to pretend an object of type A is of type B. It is not.
Any usage of the reference b will therefore yield undefined behaviour.
With your compiler, you got lucky (or unlucky, depending on how you look
at it) - the undefined behaviour happened to manifest in a way that you
expected.
struct base
{
int value;
int get() const { return value; }
void set(int v) { value = v; }
};
struct A: base
{
void doA() { set(42); }
};
struct B: base
{
int doB() { return get(); }
};
int main()
{
A a;
a.doA();
//B &b = static_cast<B &>(static_cast<base &>(a));
B &b = reinterpret_cast<B &>(a);
return b.doB();
}
It really depends on what you are actually trying to achieve.
A better way is to move the operations doA() and doB() into
the base class, possibly as polymorphic functions. But this
does not allow you to force an object of type A to magically morph
into a type B - it requires that the base class offer a more complete
set of operations.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]