Question 18
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <memory>
struct Shipping { virtual int cost(int kg) const = 0; virtual ~Shipping() = default; };
struct Standard : Shipping { int cost(int kg) const override { return 40 + 10 * kg; } };
struct Express : Shipping { int cost(int kg) const override { return 100 + 20 * kg; } };
class Order {
int kg_;
std::unique_ptr<Shipping> ship_;
public:
Order(int kg, std::unique_ptr<Shipping> s) : kg_(kg), ship_(std::move(s)) {}
void set_shipping(std::unique_ptr<Shipping> s) { ship_ = std::move(s); }
int total() const { return 500 + ship_->cost(kg_); }
};
int main() {
Order o(3, std::make_unique<Standard>());
std::cout << o.total() << ' ';
o.set_shipping(std::make_unique<Express>());
std::cout << o.total() << '\n';
return 0;
}
- A 570 660 Correct
- B 570 570
- C 540 660
- D 660 570
Correct Answer: Option A
Order depends on the Shipping interface (strategy pattern), so the algorithm can be replaced at run time: 500 + 70, then 500 + 160.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!