Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Immutable object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== C++ === In C++, a [[const-correctness|const-correct]] implementation of <code>Cart</code> would allow the user to create instances of the class and then use them as either <code>const</code> (immutable) or mutable, as desired, by providing two different versions of the <code>items()</code> method. (Notice that in C++ it is not necessary β and in fact impossible β to provide a specialized constructor for <code>const</code> instances.) <syntaxhighlight lang="cpp"> class Cart { public: Cart(std::vector<Item> items): items_(items) {} std::vector<Item>& items() { return items_; } const std::vector<Item>& items() const { return items_; } int ComputeTotalCost() const { /* return sum of the prices */ } private: std::vector<Item> items_; }; </syntaxhighlight> Note that, when there is a data member that is a pointer or reference to another object, then it is possible to mutate the object pointed to or referenced only within a non-const method. C++ also provides abstract (as opposed to bitwise) immutability via the <code>mutable</code> keyword, which lets a [[member variable]] be changed from within a <code>const</code> method. <syntaxhighlight lang="cpp"> class Cart { public: Cart(std::vector<Item> items): items_(items) {} const std::vector<Item>& items() const { return items_; } int ComputeTotalCost() const { if (total_cost_) { return *total_cost_; } int total_cost = 0; for (const auto& item : items_) { total_cost += item.Cost(); } total_cost_ = total_cost; return total_cost; } private: std::vector<Item> items_; mutable std::optional<int> total_cost_; }; </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)