Immutable object: Difference between revisions

Content deleted Content added
Link suggestions feature: 3 links added.
Tags: Mobile edit Mobile web edit
 
Line 97:
 
=== C++ ===
In C++, a [[const-correctness|const-correct]] implementation of <code>CartShoppingCart</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 CartShoppingCart {
private:
public:
Cart( std::vector<ItemMerchandise> items): items_(items) {};
public:
explicit Cart(std::vector<Item> items_;items):
items{items} {}
 
std::vector<ItemMerchandise>& items() { return items_; }
const std::vector<Item>& items() const { return items_items; }
}
 
const std::vector<Item>& items() const {
int ComputeTotalCost() const { /* return sum of the prices */ }
return *total_cost_items;
}
 
double computeTotalCost() const {
private:
return std::ranges::accumulate(
std::vector<Item> items_;
items | std::views::transform([](const Merchandise& m) -> double { return m.getPrice(); }), 0.0
);
}
};
</syntaxhighlight>
Line 119 ⟶ 128:
 
<syntaxhighlight lang="cpp">
class CartShoppingCart {
private:
public:
Cart( std::vector<ItemMerchandise> items): items_(items) {};
mutable std::optional<int> total_cost_totalCost;
public:
explicit Cart(std::vector<Merchandise> items): items{items} {}
 
const std::vector<ItemMerchandise>& items() const {
return items_items; }
 
int ComputeTotalCost() const {
if (total_cost_) {
return *total_cost_;
}
 
int total_costcomputeTotalCost() =const 0;{
for (const auto& item :if items_(!totalCost) {
totalCost = std::ranges::accumulate(
total_cost += item.Cost();
items | std::views::transform([](const Merchandise& m) -> double { return m.getPrice(); }), 0.0
);
}
return total_cost*totalCost;
}
total_cost_ = total_cost;
return total_cost;
}
 
private:
std::vector<Item> items_;
mutable std::optional<int> total_cost_;
};
</syntaxhighlight>