[ create a new paste ] login | about

Link: http://codepad.org/M0jzlq0n    [ raw code | output | fork | 1 comment ]

RogerPate - C++, pasted on Oct 27:
struct A { int a; };
struct B { int b; };
struct C : A, B {};

int main() {
  C c;
  B* pb = &c; // converting the pointer here actually adjusts the address

  void* pvc = &c; // doesn't adjust, merely type conversion
  void* pvb = pb; // doesn't adjust, merely type conversion

  cout << boolalpha;
  cout << (pvc == pvb) << '\n'; // prints false
  cout << (&c == pb) << '\n'; // prints true!
                              // (&c is converted to a B* for the comparison)

  C *pc = static_cast<C*>(pb); // this static_cast, which is UB if pb doesn't
    // actually point to a C object, also adjusts the address

  cout << (pc == &c) << '\n'; // prints true

  return 0;
}


Output:
1
2
3
false
true
true


Create a new paste based on this one


Comments:
posted by RogerPate on Oct 27
reply