Sobes.tech
Junior — Middle

Can you explain what a mutable object means in programming?

sobes.tech AI

Answer from AI

A mutable object in programming is an object whose state can be changed after its creation. For example, in C++, an object of a class with mutable fields can be modified by changing the values of these fields directly or through methods.

Example:

#include <iostream>

class MyClass {
public:
    int value;
    MyClass(int v) : value(v) {}
    void setValue(int v) { value = v; }
};

int main() {
    MyClass obj(10);
    std::cout << obj.value << std::endl; // 10
    obj.setValue(20); // changing the object's state
    std::cout << obj.value << std::endl; // 20
    return 0;
}

Unlike mutable objects, immutable objects do not allow changing their state after creation.