Structure mapping using reinterpret_cast.
Hi all,
I would like to check if a certain technique can be used or whether
there is any entry in the standard that prohibits it explicitly. If I
recall correctly, the standard guarantees that two structures
containing the same starting data members can be mapped on one another
and these common members can be access without yielding undefined
behaviour. That is, given :
struct A { int a; int b; };
struct B { int c; };
the following code is guaranteed to work :
A a;
B &b = *reinterpret_cast<B *>(&a);
b.c = 12;
assert(a.a == b.c);
And this assert should never fail.
By extension, if that is true, the following code should be guaranteed
to work :
#include <iostream>
// Base class containing the data.
class A
{
public:
A( int val = 0 ) : val_(val) { }
protected:
int get_value( ) const
{ return val_; }
private:
int val_;
};
// Interface class that uses A's data.
class B : public A
{
public:
int function( ) const
{ return get_value() / 2; }
};
// Another interface class that uses A's data.
class C : public A
{
public:
int function( ) const
{ return get_value() * 2; }
};
int main( )
{
A *a = new A(12);
B *b = reinterpret_cast<B *>(a);
std::cout << b->function() << "\n";
C *c = reinterpret_cast<C *>(a);
std::cout << c->function() << "\n";
delete a;
}
If this isn't the case, could anyone quote the entry in the standard
that states this code yields undefined behavior ?
Thanks for your time,
Olivier.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]