2

I have a class which is overloading ampersand(&) operator and made it private. I don't have a latest C++11 compliant compiler so is there any way by which I can get address of my object using current C++ compiler only

Thanks

anonymous
  • 1,920
  • 2
  • 20
  • 30
  • If you have control over object definition, use `new` and get the address of the object from the pointer. – HAL Sep 25 '13 at 09:51

2 Answers2

2
reinterpret_cast<T *>(&reinterpret_cast<char&>(obj))

Dunno if it's safe though.. (well clearly it's a bit dodgy)

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • It’s not at all dodgy, it just doesn’t take into account cv-qualification. Also, the outer cast could be a `static_cast`. – Konrad Rudolph Sep 25 '13 at 09:59
  • That's what Boost does too (with the addition of a `const volatile` to the `char&` type). – nickie Sep 25 '13 at 10:01
  • @KonradRudolph I prefer reinterpret_cast for this – Neil Kirk Sep 25 '13 at 10:04
  • @NeilKirk It’s not really a matter of preference. You should always choose the least powerful cast possible to strengthen type safety and avoid errors. Using `reinterpret_cast` circumvents most of the type system and is an inherently unsafe action, which should therefore be avoided as much as possible. – Konrad Rudolph Sep 25 '13 at 10:08
  • @KonradRudolph I don't think static_cast would even compile. – Neil Kirk Sep 25 '13 at 10:19
  • @Neil You’re right of course. My mistake – I was thinking of `void*`, not `char*`. – Konrad Rudolph Sep 25 '13 at 10:28
  • @KonradRudolph but 2 `static_casts`s could do it instead of 1 `reinterpret_cast` – user1095108 Sep 25 '13 at 10:42
  • @user1095108 This is where I prefer to use reinterpret_cast instead of chains of static_casts. It's a bit dodgy, so the code should appear as such. – Neil Kirk Sep 25 '13 at 10:46
  • @user1095108 No, that’s illegal because it violates aliasing rules. When casting to `void*`, the only legal cast is back to the same type, not to any other type. – Konrad Rudolph Sep 25 '13 at 11:51
1

Use the addressof() function from Boost.Utility. If you don't want to use Boost, you can still look at it's implementation which consists of just a single header.

Oberon
  • 3,219
  • 15
  • 30