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 deriving from 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 bad practice. But just out of curiosity: is this guaranteed to work? Is it defined behaviour?
Bonus question: Have you ever had to use such an ugly hack?
BritneySpears::getValue()
andAshtonKutcher::getValue()
simply return 0. – SulfanilamideA
andB
but I knew it would have been less much fun :D – KatharynkatheBritneySpears
in an example with undefined behavior. – Arbela