In this article we will discuss if rvalues is immutable or it can be modified in C++?

If you dont know the basics of lvalue and rvalue then we suggest to go through our previous article. In which we discussed the basics of lvalues and rvalues. i.e.

Difference between lvalue and rvalue in C++

We can not take the address of rvalue and it can not persist beyond a single expression. But can we modify rvalues ? Answer to this question has two different answers based on data type of rvalue i.e.

rvalues of builtin data type is Immutable

We can not modify the rvalue of builtin data type i.e.

Here getData() is a rvalue of buildin data type int and if we try to modify it then it will result in compile error i.e

rvalue of User Defined data type is not Immutable

rvalue of User Defined Data type can be modified. But it can be modified in same expression using its own member functions only. Let’s see an example,

Create a User Defined Data Type i.e. a class of Person i.e.

It has an incrementAge() member function that modifies it’s state i.e. increments mAge data member. Now create a function that will return Person’s object as a rvalue i.e.

Now getPerson() is a rvalue and we can not take its address i.e.

But we can modify this rvalue because it is of User Defined Data type (of Person class) i.e.

Here we have modified a rvalue of Person Class Type with its member function in the same expression.

This proves that we can modify the rvalue of  User Defined Data type with its own member function but in the same expression because rvalue persist in single expression only.

Checkout the complete example as follows,

In next article we will discuss what is a rvalue reference.