Mutable vs Immutable Objects

A mutable object can be changed after it's created, and an immutable object can't.

In C++, everything is mutable by default:

vector<int> mutable_vector = {4, 9}; mutable_vector[0] = 1; // mutable_vector is now [1, 9]

But if an object is declared with the const keyword, then it's immutable:

const vector<int> immutable_vector = {4, 9}; immutable_vector[0] = 1; // Won't compile, since we're modifying something // declared const.

C++ will let you cast away the const keyword, but it's only safe when the underlying variable isn't declared const. Otherwise, the behavior is undefined!

int plain_int = 42; const int& const_int = plain_int; const_int = 24; // Won't complie, since we're assigning to something declared const. const_cast<int&>(const_int) = 24; // Compiles. Safe, since plain_int wasn't declared const. // plain_int and const_int are now 24 const vector<int> immutable_vector = {4, 9}; immutable_vector[0] = 1; // Won't compile, since we're modifying something declared const const_cast<vector<int>&>(immutable_vector)[0] = 1; // Complies, but behavior is undefined, since immutable_vector was declared const! // Don't do this!

Strings can be mutable or immutable in C++ depending on whether they're declared const:

string testString("mutable?"); testString[7] = '!'; // testString is now "mutable!"
const string testString("mutable?"); testString[7] = '!'; // compile-time error

Mutable objects are nice because you can make changes in-place, without allocating a new object. But be careful—whenever you make an in-place change to an object, all references to that object will now reflect the change.

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .