LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Polymorphism Programs · Question 1

Payment gateway with polymorphic payment methods in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write an abstract PaymentMethod with virtual fee() and name(), implement UPI, Card and NetBanking with different fee rules, and process a list of payments through base-class pointers.

Solution
main.cpp
#include <format>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class PaymentMethod {
public:
    virtual double fee(double amount) const = 0;
    virtual std::string name() const = 0;
    double total(double amount) const { return amount + fee(amount); }
    virtual ~PaymentMethod() = default;
};

class Upi : public PaymentMethod {
public:
    double fee(double) const override { return 0; }
    std::string name() const override { return "UPI"; }
};
class Card : public PaymentMethod {
public:
    double fee(double a) const override { return a * 0.018; }
    std::string name() const override { return "Card"; }
};
class NetBanking : public PaymentMethod {
public:
    double fee(double a) const override { return a < 1000 ? 10 : 15; }
    std::string name() const override { return "NetBanking"; }
};

int main() {
    std::vector<std::pair<std::unique_ptr<PaymentMethod>, double>> orders;
    orders.emplace_back(std::make_unique<Upi>(), 499);
    orders.emplace_back(std::make_unique<Card>(), 2500);
    orders.emplace_back(std::make_unique<NetBanking>(), 750);
    for (const auto& [m, amt] : orders)
        std::cout << std::format("{:<11}{:>8.2f} + fee {:>6.2f} = {:>8.2f}\n", m->name(), amt, m->fee(amt), m->total(amt));
    return 0;
}

Output Verified by compiling and running

UPI          499.00 + fee   0.00 =   499.00
Card        2500.00 + fee  45.00 =  2545.00
NetBanking   750.00 + fee  10.00 =   760.00

The checkout loop never asks which method it has; each class supplies its own fee rule. Adding a Wallet means writing one new class and changing nothing else (open/closed principle).

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