Is private members hacking a defined behaviour ?

Posted by ereOn on Stack Overflow See other posts from Stack Overflow or by ereOn
Published on 2010-05-14T13:18:35Z Indexed on 2010/05/14 13:24 UTC
Read the original article Hit count: 291

Filed under:
|
|
|

Hi,

Lets say I have the following class:

class BritneySpears
{
  public:

    int getValue() { return m_value; };

  private:

    int m_value;
};

Which is an external library (that I can't change). I obviously can't change the value of m_value, only read it. Even subclassing BritneySpears won't work.

What if I define the following class:

class AshtonKutcher
{
  public:

    int getValue() { return m_value; };

  public:

    int m_value;
};

And then do:

BritneySpears b;

// Here comes the ugly hack
AshtonKutcher* a = reinterpret_cast<AshtonKutcher*>(&b);
a->m_value = 17;

// Print out the value
std::cout << b.getValue() << std::endl;

I know this is a bad practice.

But just for curiosity: is this guaranted to work ? Is it a defined behaviour ?

Bonus question: Have you ever had to use such an ugly hack ?

Thanks !

© Stack Overflow or respective owner

Related posts about c++

Related posts about hacks