Re: Structure mapping using reinterpret_cast.
Antoon wrote:
"Olivier" <olivier.grant@gmail.com> schreef in bericht
news:b7c86c21-b9d4-44fb-b4f3-d619975bbfbc@q37g2000vbi.googlegroups.com...
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 ?
This is actually how many of the MFC classes like CButton, CEdit,
etc. (used to) work.
They don't have to strictly follow the C++ standard, as they have the
advantage of being tied to a certain compiler - anything they do could
be implementation specific. Just make a deal between the library
writer and the compiler team!
User code does not generally have this opportunity. :-)
Bo Persson
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]