On Jun 7, 7:15 am, wschlan...@gmail.com wrote:
Hi, the following code works as expected, e.g. it prints 1234. How can
this be if the address of C2::x is 0 or 1?? Why does the printf that
prints the address of C2::x, print a 0 or 1 instead of its real
address? What am I missing here?
That the code has undefined behavior.
This is typical of the mess you get into if you use printf.
Don't. std::ostream works a lot better.
--
#include <stdio.h>
class C2
{
public:
int x;
};
class C1 :
public C2
{
public:
void f()
{
C2::x = 0x1234;
printf("%x\n", C2::x);
Undefined behavior. The %x formatter requires an unsigned int,
and not an int.
In practice, it's hard to imagine an implementation where this
won't work, but formally, you need to write:
printf( "%x\n", (unsigned int)C2::x ) ;
//The following line prints 0 or 1
printf("%x\n", &C2::x);
Undefined behavior. About the only way to legally output the
contents of a pointer to member is to assign it to a variable
and then use some sort of ugly type punning using reinterpret
cast:
int C2::*pi = &C2::i ;
printf( "%x\n", reinterpret_cast< unsigned int& >( pi ) ) ;
Even this will not work if the size of the pointer to member is
not the same as the size of an int.
Typically, a pointer to a data member will be implemented as
some integral type (probably a size_t) containing the offset of
the member from the start of the class. Sometimes, this offset
will be incremented by one so that the null pointer
representation can be all bits 0; historically, there's a lot of
code out there that assumes that memset(...,0,...) will cause
any pointers to be null pointer. Such code is wrong, but
compiler vendors don't like proving their customers to be
idiots.
//The following line will not even compile. WHY???
//printf("%x\n", (unsigned)(&C2::x));
Because the standard doesn't define any such conversion.
}
};
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34