Sunday, June 22, 2008

Creating An Immutable Object

An immutable object is an object that once gets created can no longer changed its state afterwards.
For example, to make a class immutable we can do the following:

class A
{
//1. we make its attributes private.
int x,y;
public:
//2. only create getters if needed, no setters of course
int getx() const {return x;} //same for y
public:
//3. declare an explicit constructor
explicit A(int _x, int _y) : x(_x), y(_y){}
};

We make the attributes private so derived classes cannot change the state. Of course, getters should return copies not references to the attribute.

2 comments:

Anonymous said...

I like the subjects(C++/Boost) on which you write on your blog. Please continue writing if you have got free time.

Mailund said...

if you want As to be immutable, you could also just make x and y const.

It won't quite be as immutable, 'cause it is possible to cast the const'ness away, but still ;)