LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 16

Polymorphism with std::variant and std::visit Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <string>
#include <variant>
#include <vector>

struct Card  { double amount; };
struct Cash  { double amount; };
struct Wallet { std::string app; double amount; };

struct Fee {
    double operator()(const Card& c) const { return c.amount * 0.02; }
    double operator()(const Cash&) const { return 0; }
    double operator()(const Wallet& w) const { return w.amount > 1000 ? 5 : 0; }
};

int main() {
    std::vector<std::variant<Card, Cash, Wallet>> payments{Card{500}, Cash{200}, Wallet{"PayNow", 1500}, Card{1000}};
    double fees = 0;
    for (const auto& p : payments) fees += std::visit(Fee{}, p);
    std::cout << fees << ' ' << payments[2].index() << '\n';
    return 0;
}
  • A 35 2 Correct
  • B 30 2
  • C 35 3
  • D 15 2
Correct Answer: Option A

std::visit calls the Fee overload matching the type currently held: 10 + 0 + 5 + 20 = 35. index() reports which alternative is held (Wallet is the third, index 2).

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links