Is rvalue immutable in C++?

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.

(x+7) = 7; // Compile error - Can not Modify rvalue
int getData();

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

getData() = 9; // Compile Error - Can not modify rvalue

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.

class Person {
	int mAge;
public:
	Person() {
		mAge = 10;
	}
	void incrementAge()
	{
		mAge = mAge + 1;
	}
};

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.

Person getPerson()
{
	return Person();
}

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

Person * personPtr = &getPerson(); // COMPILE ERROR

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

getPerson().incrementAge();

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,

#include <iostream>

class Person {
	int mAge;
public:
	Person() {
		mAge = 10;
	}
	void incrementAge()
	{
		mAge = mAge + 1;
	}
};
Person getPerson()
{
	return Person();
}
int main() {

//	Person * personPtr = &getPerson();

	getPerson().incrementAge();

	return 0;
}

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

[showads ad=inside_post]

 

Thanks.

 

1 thought on “Is rvalue immutable in C++?”

Leave a Reply to Kranti Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top