Search code examples
c++privateencapsulationreinterpret-cast

What is happening here in this C++ program?


I was reading this excellent article Uses & Abuses of Access Rights. I didn't understand following example from that.

File: x.h

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

  template<class T>
  void f( const T& t ) { /*...*/ }

  int Value() { return private_; }

private: 
  int private_; 
};

File: break.cpp

#include "x.h"
#include <iostream>
class BaitAndSwitch
    // hopefully has the same data layout as X
{   // so we can pass him off as one
  public:
  int notSoPrivate;
};

void f( X& x )
{
  // evil laughter here
  (reinterpret_cast<BaitAndSwitch&>(x)).notSoPrivate = 2;
}
int main()
{
    X x;
    std::cout<<x.Value()<<'\n';
    f(x);
    std::cout<<x.Value()<<'\n';
}

How this program works? What's actually happening in global function f()? Please someone clearly explain how the value of private variable gets changed?

Why herb sutter said that the object layouts of X and BaitAndSwitch are not guaranteed to be the same, although in practice they probably always will be? Is this program well defined?


Solution

  • The casting is remapping the private area into a public one in a new structure. This behavior is not guaranteed to work (though it is probably stable) as the layout of structures internally is not set.

    It is really no different than grabbing a pointer and writing something into it, although it is done is a bit more precise way.