2011-02-09

Reusing bits

I was cleaning my projects directory and I have stumbled upon a small piece of code which I thought might interest others.

The small piece of code was about changing a private data member from outside the object, using normal C++, without using reintepret_cast or hacks like #define class struct


#include <iostream>

class Pi
{
    double pi_;
public:
    Pi() : pi_(3.1514f)
    {
    }

    double GetValue() const
    {
        return pi_;
    }
};

struct Pie
{
    double pie_;
};

int main()
{
    using std::cout;
    using std::endl;

    Pi pi;
   
    cout << "Pi: " << pi.GetValue() << endl;

    Pie* p = new (&pi) Pie;
   
    p->pie_ = 4.0f;

    cout << "Pi: " << pi.GetValue() << endl;
}

I have highlighted the line which does the trick. This trick is called placement new.
Post a Comment