c++ - Pointer values are different but they compare equal. Why? -


a short example outputs weird result!

#include <iostream>  using namespace std;  struct { int a; };     struct b { int b; }; struct c : a, b {     int c; };  int main() {     c* c = new c;     b* b = c;      cout << "the address of b 0x" << hex << b << endl;     cout << "the address of c 0x" << hex << c << endl;      if (b == c)     {         cout << "b equal c" << endl;     }     else     {         cout << "b not equal c" << endl;     } } 

it's surprising me output should follows:

the address of b 0x003e9a9c address of c 0x003e9a98 b equal c 

what makes me wonder is:

0x003e9a9c not equal 0x003e9a98, output "b equal c"

a c object contains 2 sub-objects, of types a , b. obviously, these must have different addresses since 2 separate objects can't have same address; @ 1 of these can have same address c object. why printing pointers gives different values.

comparing pointers doesn't compare numeric values. pointers of same type can compared, first 1 must converted match other. in case, c converted b*. same conversion used initialise b in first place: adjusts pointer value points b sub-object rather c object, , 2 pointers compare equal.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -