2
votes

You can't modify immutable Python objects, you may simply create new objects with new values:

n = 1
id(n)
output: 123
n = n + 1
id(n)
output: 140

You can modify mutable objects though:

m = [1]
id(m)
output: 210
m.append(2)
id(m)
output: 210

I'm wandering, what is the closest concept to Python's mutable/immutable objects in C/C++?

2
const/constexpr objects & const methodscageman

2 Answers

1
votes

Simple: const objects

More complex: since python follows reference semantics everything can be roughly thought of as a generic pointer. A pointer that can be reassigned, but what it points to can't be changed is a pointer to const, which is I think what you want.

int i;
int j;
const int *p =&i;
p = &j;
*p = 1; // error

However, since python dynamically allocates its objects, and C doesn't not unless told to do so, can't do something like the following and get the same behavior as python

*p = *p + 1;

So it's still lacking, but it's the closest I think you can get without making something really contrived.

1
votes

Immutability is a concept usually found in functional programming (although it can be important to OOP too):

https://en.wikipedia.org/wiki/Immutable_object

C/C++ have immutability (through const) but are mostly built around mutability (C more so than C++) because of pointers and the ability to access/modify arbitrary memory owned by the process. Even const has loopholes:

https://en.wikipedia.org/wiki/Const_%28computer_programming%29#Loopholes_to_const-correctness