The essential point of immutability is preventing value modification. In C++ programming language, there is a keyword to prevent the code modifying a value. The keyword is const and we are going to use it in the const.cpp code. We have a class named MyAge which contains a public field named age and we set it as const. We will play with this const field and the code will look like following:
/* const.cpp */
#include <iostream>
using namespace std;
// My Age class will store an age value
class MyAge
{
public:
const int age;
MyAge(const int initAge = 20) :
age(initAge)
{
}
};
auto main() -> int
{
cout << "[const.cpp]" << endl;
// Initializing several MyAge variables
MyAge AgeNow, AgeLater(8);
// Displaying age property...