2

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++?

asked Dec 11, 2014 at 19:59
1
  • 1
    const/constexpr objects & const methods
    cageman
    Commented Dec 11, 2014 at 20:19

2 Answers 2

1

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.

answered Dec 11, 2014 at 20:21
0
1

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

answered Dec 11, 2014 at 20:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.