Can one access private member functions through casting to layout-compatible types?

Viewed 2301

From the discussion of this question How is access for private variables implemented in C++ under the hood? I posed a variation: instead of accessing a private data member, can one call private member functions through casting and relying on layout-compatibility?

Some code (inspired by Herb Sutter's column Uses and Abuses of Access Rights )

#include <iostream>

class X 
{ 
public:
  X() : private_(1) { /*...*/ }

private: 
  int Value() { return private_; }
  int private_; 
};

// Nasty attempt to simulate the object layout
// (cross your fingers and toes).
//
class BaitAndSwitch
    // hopefully has the same data layout as X
{   // so we can pass him off as one
public:
  int Value() { return private_; }
private:
  int private_;
};

int f( X& x )
{
  // evil laughter here
  return (reinterpret_cast<BaitAndSwitch&>(x)).Value();
}

int main()
{
    X x;
    std::cout << f(x) << "\n"; // prints 0, not 1
    return 0;
}; 

Note: this works (at least on Ideone)! Is there any way the new C++11 Standard gives a guaranteed or at least an implementation-defined way to circumvent the access control by relying on layout-compatibility and reinterpret_cast / static_cast?

EDIT1: output on Ideone

EDIT2: In Sutter's column he lists two reasons why the above code is not guaranteed to work (although it works in practice)

a) The object layouts of X and BaitAndSwitch are not guaranteed to be the same, although in practice they probably always will be.

b) The results of the reinterpret_cast are undefined, although most compilers will let you try to use the resulting reference in the way the hacker intended.

Does the new C++11 Standard now provide these layout / reinterpret_cast guarantees?

1 Answers
Related