C++: Enforced Immutability


Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.

In addition to the examples shown in C, you can create a class whose instances contain instance-specific const members, by initializing them in the class’s constructor.

#include <iostream>

class MyOtherClass
	const int m_x;
	MyOtherClass(const int initX = 0) : m_x(initX) { }


int main()
	MyOtherClass mocA, mocB(7);

	std::cout << mocA.m_x << std::endl; // displays 0, the default value given for MyOtherClass's constructor.
	std::cout << mocB.m_x << std::endl; // displays 7, the value we provided for the constructor for mocB.

	// Uncomment this, and the compile will fail; m_x is a const member.
	// mocB.m_x = 99;

	return 0;

You can also use the const keyword on methods to indicate that they can be applied to immutable objects:

class MyClass
	int x;

	int getX() const
		return x;


Content is available under GNU Free Documentation License 1.2.