Skip to content

Adapter

Difficulty: Intermediate

Key concepts

  • adapter pattern
  • object adapter
  • class adapter
  • system boundary
  • exception translation
  • target interface
  • What the Adapter pattern is for: using a class that does the right job but has the wrong interface, without changing either side.
  • How to write an object adapter in modern C++: a small class that implements the interface your code wants and holds the class it adapts.
  • What an adapter at a system boundary translates: units, codes, error reporting, and exceptions, so that a vendor’s terms do not spread through your code.
  • The other forms: the class adapter, a lambda as a function adapter, and the adaptors in the standard library.
  • When an adapter is the wrong tool.

An online shop takes card payments. The payment service is OldPay, whose library the shop has used for years.

  1. FR-1 Charge the customer’s card for an order, and tell the customer the result: paid, with a reference; declined, with a reason they can read; or not charged yet, when the problem is temporary and the shop will try again.
  2. FR-2 Use OldPay’s library to take the payment.
  3. FR-3 Tests of the checkout must not depend on OldPay’s library, its test cards, or its result codes.
  4. C-1 (constraint) The shop cannot change OldPay’s library. It comes from the vendor as a header and a compiled library.

The shop’s card form already turns the card number into a token, so the shop’s own code never sees card numbers.

OldPay’s library is older than the shop’s code, and it shows. In this example it is a stub written for the page, so that it can run without a real payment service, but its style is typical of real vendor libraries:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

oldpay.hpp
// The vendor's answer to one authorize() call: a number saying what
// happened, and, for an approved payment, a reference such as
// "OP-000001" that identifies the payment later. The shop has to know
// what each number means, which is exactly what the adapter will hide.
struct Response {
int code = 0; // 0 approved, 51 no funds, 54 expired card,
// 91 card issuer unavailable; any other code declines
// (this stub also returns 12, 13, and 14; see oldpay.cpp)
std::string reference; // set only when approved
};
// Thrown when the terminal cannot reach the vendor. Not a std::exception:
// it does not derive from std::exception, so a `catch (const
// std::exception&)` would let it fly past. Only a catch for
// oldpay::LinkDown itself (or catch (...)) stops it. `detail` says what
// went wrong, in the vendor's words.
struct LinkDown {
std::string detail;
};
// The vendor's object for taking payments. The shop creates one, then
// calls authorize() once per payment. This is the class being adapted
// (the "adaptee"): it does the right job, but in the vendor's terms.
class Terminal {
public:
// merchant_id: which shop is charging. The stub keeps it but does not
// use it; a real terminal would send it to the vendor.
explicit Terminal(std::string merchant_id);
// Asks the vendor to take `amount` in `currency` from the card behind
// `card_token`. Returns a Response with a code, or throws LinkDown
// when the vendor cannot be reached.
// amount: major units with exactly two decimals, such as "12.34".
// currency: an ISO 4217 numeric code, such as 978 for euros.
Response authorize(const std::string& card_token, const std::string& amount, int currency);
// Only in this stub: every amount and currency it was given, so tests
// can check what the shop sent. Public on purpose, so a test can read
// it directly; each entry looks like "12.34 978".
std::vector<std::string> log;
private:
std::string merchant_id_;
int next_reference_ = 1; // the number in the next approval's reference
};

The stub decides the answer from the card token, the way vendors’ test environments often do: tok_ok is approved, tok_expired returns code 54, tok_offline throws. Its public log exists only in the stub, so tests can see exactly what the shop sent.

Set the vendor’s terms against the shop’s:

Concern The shop thinks in OldPay expects or returns
amount whole cents, std::int64_t: 1234 text in major units with two decimals: "12.34"
currency an enum class Currency { eur, usd, gbp } an ISO 4217 numeric code: 978, 840, 826
result paid, declined, or try again later, with a reason an int code: 0, 51, 54, 91, or any other
“cannot reach it” a temporary problem: try again later throws oldpay::LinkDown, which is not a std::exception

The two sides do the same job in different words. That mismatch, and not any missing behaviour, is the problem this page solves.

Call the vendor directly from the checkout:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// The checkout with no adapter: one function that charges the order
// through OldPay and returns a message for the customer. It works, but it
// mixes the shop's job (the message) with the vendor's terms (text
// amounts, currency numbers, result codes, LinkDown). Throws
// std::invalid_argument for an amount of zero or less.
std::string pay_for_order(const ChargeRequest& request, oldpay::Terminal& terminal) {
if (request.amount_cents <= 0) {
throw std::invalid_argument{"a charge must be for more than zero"};
}
// Vendor detail 1: cents to text such as "12.34". `%` gives the cents
// left over (34), `/` the whole units (12), and a remainder under 10
// gets a leading zero, so 5 cents becomes "0.05".
const std::int64_t part = request.amount_cents % 100;
const std::string amount =
std::to_string(request.amount_cents / 100) + (part < 10 ? ".0" : ".") + std::to_string(part);
// Vendor detail 2: Currency to OldPay's number, as a chain of `?:`
// ("if eur then 978, else if usd then 840, else 826"). The last branch
// catches everything else, so a currency added to the enum later would
// silently be sent as 826 (pounds), with no compiler warning.
const int currency = request.currency == Currency::eur ? 978
: request.currency == Currency::usd ? 840
: 826;
const std::string order = "order " + request.order_id + ": ";
// Declared before the try, so it is still in scope after the try ends.
oldpay::Response response;
try {
response = terminal.authorize(request.card_token, amount, currency);
} catch (const oldpay::LinkDown& error) {
// Vendor detail 3: the vendor's own exception type, in the checkout.
return order + "not charged yet, will retry (payment service unreachable: " +
error.detail + ")";
}
// Vendor detail 4: OldPay's codes, each turned into words right here.
// Any code not listed falls through to the last return, a decline.
if (response.code == 0) {
return order + "paid " + display_amount(request.amount_cents, request.currency) +
", reference " + response.reference;
}
if (response.code == 91) {
return order + "not charged yet, will retry (card issuer unavailable)";
}
if (response.code == 51) {
return order + "declined (insufficient funds)";
}
if (response.code == 54) {
return order + "declined (card expired)";
}
return order + "declined (declined by the payment service, code " +
std::to_string(response.code) + ")";
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// `orders` holds three ChargeRequests, made above: A-1001 (tok_ok,
// 1234 cents, EUR), A-1002 (tok_expired, 5000, EUR), and A-1003
// (tok_offline, 805, GBP). The checkout is handed the vendor's
// Terminal itself.
oldpay::Terminal old_terminal{"shop-42"};
for (const ChargeRequest& order : orders) {
std::cout << "before: " << before::pay_for_order(order, old_terminal) << '\n';
}

It works, and for a program that will only ever talk to OldPay and needs no tests of the checkout, it would be acceptable. Look at what the function is doing, though:

  • Three jobs in one function. It decides what to tell the customer (the shop’s job), converts cents and currencies into OldPay’s format, and interprets OldPay’s codes and exception (both about the vendor).
  • The vendor’s terms are in the shop’s code. Codes 51, 54, and 91, the currency number 978, and oldpay::LinkDown appear in the checkout. Every other place that takes a payment, such as a refund or a subscription renewal, would repeat them.
  • FR-3 fails. A checkout test must use OldPay’s library and know its test tokens:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_payments.cpp
// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)
// records a failure, printing both values, if they are not equal. Both
// come from the site's small test header, lld_test.hpp.
// To test how the checkout reports an expired card, the test must know
// which vendor token the stub turns into the vendor's code 54.
LLD_TEST(before_a_checkout_test_is_written_in_the_vendors_terms) {
oldpay::Terminal terminal{"test"};
// tok_expired is the stub's test token for code 54: vendor knowledge.
const ChargeRequest request{"T-1", "tok_expired", 1000, Currency::eur};
LLD_CHECK_EQ(before::pay_for_order(request, terminal),
std::string{"order T-1: declined (card expired)"});
}

The test is about the checkout’s message, but it is written in the vendor’s terms: a reader must know that tok_expired becomes code 54, and code 54 becomes “card expired”.

Ask, for each piece of data and each job, whose terms it is in:

Data or job Whose terms Where it goes
the order, card token, amount in cents, and currency the shop’s ChargeRequest, a plain struct the shop defines
paid, declined, or try again later, with a reference or reason the shop’s ChargeStatus and ChargeResult, defined by the shop
“charge this request” the shop’s the target interface PaymentGateway, which the shop owns
the message to the customer the shop’s pay_for_order, which uses only PaymentGateway
cents to "12.34", Currency to 978 translation the adapter
code 54 to “declined, card expired”; LinkDown to “try again later” translation the adapter
talking to the payment network the vendor’s oldpay::Terminal, unchanged (C-1)

The shop’s side and the vendor’s side each stay in their own terms. Everything that knows both goes in one class: the adapter. It has one data member, a pointer to the Terminal it talks to, and no data of its own. Its functions are all translation; it makes no decisions about what to tell the customer.

Adapter converts the interface of an existing class into the interface its callers expect, so that classes with mismatched interfaces can work together. The adapter implements the interface the callers want, and inside each function it calls the class it adapts, translating the arguments on the way in and the results on the way out.

It has four participants:

  • The target: the interface the callers want. Here, PaymentGateway.
  • The client: the code that uses the target. Here, pay_for_order.
  • The adaptee: the existing class with the wrong interface. Here, oldpay::Terminal.
  • The adapter: implements the target, and holds and calls the adaptee. Here, OldPayGateway.
The checkout depends only on the shop's interface; the adapter implements it by calling the vendor's Terminal
Text description of the diagram

A class diagram. PaymentGateway is an interface with one pure virtual function, charge, which takes a ChargeRequest and returns a ChargeResult. OldPayGateway implements PaymentGateway. It holds a pointer to the vendor’s Terminal, which it does not own, and its constructor takes a Terminal reference. Terminal, the vendor’s class, which the shop cannot change, has authorize, taking a token, an amount as text, and a currency code, and returning a Response. The function pay_for_order uses PaymentGateway only; it does not know about OldPayGateway or Terminal.

Diagram source (Mermaid)
classDiagram
class PaymentGateway {
  <<interface>>
  +charge(const ChargeRequest&) ChargeResult*
}
class OldPayGateway {
  -Terminal* terminal_
  +OldPayGateway(Terminal&)
  +charge(const ChargeRequest&) ChargeResult
}
class Terminal {
  <<vendor, cannot change>>
  +authorize(token, amount text, currency code) Response
}
class pay_for_order {
  <<function>>
  +pay_for_order(request, gateway) string
}
PaymentGateway <|.. OldPayGateway
OldPayGateway --> Terminal : terminal_ (not owned)
pay_for_order ..> PaymentGateway : uses

The arrow that matters is the one that is missing: nothing on the shop’s side points at Terminal. Only the adapter knows the vendor exists.

The shop defines what a payment is, in its own terms:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

payments.hpp
// The currencies the shop sells in. An enum class, so a currency can only
// be one of these three names, never a stray number or string.
enum class Currency { eur, usd, gbp };
// Everything the shop knows about one payment it wants to take. A plain
// struct with public fields: it is data passed from the checkout to a
// gateway, with no rules of its own to protect.
struct ChargeRequest {
std::string order_id;
std::string card_token; // from the card form; the shop never sees card numbers
// The amount in whole cents (1234 means 12.34), as a 64-bit integer.
// Whole numbers keep money exact; a double could not hold 0.10 exactly.
std::int64_t amount_cents = 0;
Currency currency = Currency::eur;
};
// The three outcomes the shop cares about. try_again_later means "nothing
// was charged, but the same request may work later", which the checkout
// tells the customer differently from a decline.
enum class ChargeStatus { approved, declined, try_again_later };
// What a gateway reports back, in the shop's terms: no vendor codes. The
// status starts as declined, so a result made without setting it can
// never read as "paid".
struct ChargeResult {
ChargeStatus status = ChargeStatus::declined;
std::string reference; // set when approved
std::string reason; // set when not approved, in words a customer can read
// `= default` asks the compiler to write ==, comparing the three fields
// in order. The tests use it to compare a whole result in one check.
friend bool operator==(const ChargeResult&, const ChargeResult&) = default;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

payments.hpp
// What the shop needs from any payment service. This is the "target"
// interface: the shape the shop's code wants. It is an abstract class
// (an interface), so code holds a PaymentGateway& and never knows which
// vendor is behind it.
class PaymentGateway {
public:
// Virtual, so destroying a gateway through a PaymentGateway pointer
// also runs the derived class's destructor.
virtual ~PaymentGateway() = default;
// Takes one payment and reports the outcome. `= 0` makes it pure
// virtual: every concrete gateway must write its own charge, and
// PaymentGateway itself cannot be created.
virtual ChargeResult charge(const ChargeRequest& request) = 0;
protected:
// Protected, so only derived classes can use them. That stops
// `gateway_a = gateway_b` through two PaymentGateway references, which
// would copy only the base part and none of the derived class's data.
PaymentGateway() = default;
PaymentGateway(const PaymentGateway&) = default;
PaymentGateway& operator=(const PaymentGateway&) = default;
};
  • The shop owns this interface, and it is shaped by what the shop needs, not by what OldPay offers. This is the Dependency Inversion Principle at work: the vendor’s code is made to fit the shop’s interface, not the other way round.
  • The copy operations are protected, so one PaymentGateway& cannot be assigned to another, which would copy only the base part. The class is abstract, so it cannot be copied on its own either.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

oldpay_adapter.hpp
// Lets the shop charge cards through OldPay's Terminal, using the shop's
// own PaymentGateway interface. This is the adapter: on the outside it is
// a PaymentGateway (it inherits from it); on the inside it holds a
// Terminal and translates each call into the vendor's terms and back.
// `final` means no class can derive from it in turn.
class OldPayGateway final : public PaymentGateway {
public:
// Borrows the terminal, which must outlive this object. The adapter
// does not own or create the Terminal: the caller makes one and passes
// it in by reference, and the adapter keeps its address. Taking a
// non-const reference (not a pointer) means a null terminal cannot be
// passed, and a temporary such as oldpay::Terminal{"x"} is refused by
// the compiler. `explicit` stops a Terminal from silently turning into
// an OldPayGateway.
explicit OldPayGateway(oldpay::Terminal& terminal) : terminal_{&terminal} {}
// Translates the request, calls the vendor, and translates the answer.
// Throws std::invalid_argument for an amount of zero or less, before
// calling the vendor. `override` asks the compiler to check that this
// really replaces PaymentGateway::charge.
ChargeResult charge(const ChargeRequest& request) override;
private:
// The borrowed terminal. A pointer rather than a reference member, so
// an OldPayGateway can still be assigned; it never deletes the terminal.
oldpay::Terminal* terminal_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

oldpay_adapter.cpp
// The adapter's one job, in three steps: translate the request into
// OldPay's terms, call the vendor, translate the answer back.
ChargeResult OldPayGateway::charge(const ChargeRequest& request) {
// Lets this function write to_vendor_amount instead of
// oldpay_conversions::to_vendor_amount. It applies inside charge only.
using namespace oldpay_conversions;
// Step 1: convert first, outside the try. A zero amount throws
// std::invalid_argument here, before the vendor is called, and that
// exception is not caught below: it goes on to the caller.
const std::string amount = to_vendor_amount(request.amount_cents);
const int currency = to_vendor_currency(request.currency);
try {
// Steps 2 and 3 in one line: terminal_-> calls through the pointer
// to the borrowed Terminal, and its Response goes straight into
// from_vendor, whose ChargeResult is returned.
return from_vendor(terminal_->authorize(request.card_token, amount, currency));
} catch (const oldpay::LinkDown& error) {
// Only LinkDown is caught, by type. Any other exception still
// reaches the caller, so a real bug is not hidden as "try later".
// The vendor's exception stops here; callers see the shop's terms.
return {ChargeStatus::try_again_later, "", "payment service unreachable: " + error.detail};
}
}

charge is the whole pattern: translate the request, call the vendor, translate the answer. Three details matter:

  • The vendor’s exception stops here. oldpay::LinkDown is caught inside the adapter and becomes try_again_later. No caller has to know the type exists, and code that only catches std::exception would not have caught it anyway, because it is not derived from std::exception.
  • Only the vendor’s exception is caught. The adapter does not use catch (...). A zero amount is the shop’s own mistake, and to_vendor_amount reports it with std::invalid_argument before the vendor is called. Swallowing every exception would hide bugs as “try again later”.
  • Unknown codes are declines, not approvals. OldPay has many codes, and may add more. The default case treats any code it does not know as a decline, and keeps the number in the reason, so support staff can look it up. Mapping an unknown code to “paid” would ship goods that were never paid for.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

oldpay_adapter.hpp
// The three translations the adapter makes, one for each way the shop's
// terms and OldPay's differ. Exposed for tests; the shop's other code
// never calls them.
namespace oldpay_conversions {
// Throws std::invalid_argument for an amount of zero or less.
std::string to_vendor_amount(std::int64_t cents); // 1234 -> "12.34"
int to_vendor_currency(Currency currency); // Currency::eur -> 978
// A vendor code becomes approved, declined, or try_again_later, with a
// reason a customer can read: code 54 -> declined, "card expired".
ChargeResult from_vendor(const oldpay::Response& response);
} // namespace oldpay_conversions

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

oldpay_adapter.cpp
// Cents to OldPay's text: 1234 -> "12.34", 5 -> "0.05", 100000 ->
// "1000.00". Only whole-number arithmetic, so no rounding can creep in.
// Throws std::invalid_argument for zero or less: charging nothing, or a
// negative amount, is a bug in the shop, not something to send the vendor.
std::string to_vendor_amount(std::int64_t cents) {
if (cents <= 0) {
throw std::invalid_argument{"a charge must be for more than zero"};
}
// `%` is the remainder: the cents left over after whole units (34 for
// 1234), and `/` on integers drops the fraction (12 for 1234).
const std::int64_t part = cents % 100;
// A remainder under 10 needs a leading zero: 5 cents is ".05", not ".5".
// `?:` picks ".0" or "." to go between the two numbers.
return std::to_string(cents / 100) + (part < 10 ? ".0" : ".") + std::to_string(part);
}
// The shop's Currency to OldPay's ISO 4217 number. The switch lists every
// Currency and has no `default`, so with -Wall the compiler warns if a
// new currency is added to the enum and forgotten here. The throw after
// the switch is reached only by a value outside the enum (possible with
// a cast); it never sends a wrong number to the vendor.
int to_vendor_currency(Currency currency) {
switch (currency) {
case Currency::eur:
return 978;
case Currency::usd:
return 840;
case Currency::gbp:
return 826;
}
throw std::invalid_argument{"unknown currency"};
}
// OldPay's Response to the shop's ChargeResult. Each `return {a, b, c}`
// builds a ChargeResult from its three fields in order: status,
// reference, reason. Only code 0 is a payment; only code 91 is worth
// trying again; any other code, including ones OldPay adds later, falls
// to `default` and is a decline that keeps the number for support staff.
ChargeResult from_vendor(const oldpay::Response& response) {
switch (response.code) {
case 0:
// Approved: keep the vendor's reference, so the payment can be
// found again; the reason is left empty.
return {ChargeStatus::approved, response.reference, ""};
case 51:
return {ChargeStatus::declined, "", "insufficient funds"};
case 54:
return {ChargeStatus::declined, "", "card expired"};
case 91:
return {ChargeStatus::try_again_later, "", "card issuer unavailable"};
default:
return {ChargeStatus::declined, "",
"declined by the payment service, code " + std::to_string(response.code)};
}
}
How this code works: OldPayGateway::charge, with the three orders from main

charge and the three translations work together. For each order:

  1. Translate the request. to_vendor_amount turns the cents into text, and to_vendor_currency turns the Currency into OldPay’s number. Both run before the try, so a zero or negative amount throws std::invalid_argument and the vendor is never called.
  2. Call the vendor. terminal_->authorize(...) runs on the borrowed Terminal. It either returns a Response or throws LinkDown.
  3. Translate the answer. A Response goes to from_vendor, which picks a ChargeStatus and a reason from the code. A LinkDown is caught and becomes try_again_later, with the vendor’s detail in the reason.

A worked example. The three orders in main, through one new terminal:

Order Cents, currency Sent to OldPay OldPay’s answer ChargeResult
A-1001 1234, eur "12.34", 978 code 0, reference OP-000001 approved, reference OP-000001
A-1002 5000, eur "50.00", 978 code 54 (tok_expired) declined, "card expired"
A-1003 805, gbp "8.05", 826 throws LinkDown, “no route to the payment host” try_again_later, "payment service unreachable: no route to the payment host"

For A-1003, 805 % 100 is 5, which is under 10, so ?: picks ".0" and the text is "8" + ".0" + "5", that is "8.05". Only an approved payment uses up a reference number, so a second approval on the same terminal would get OP-000002.

  • The amount is converted with whole numbers. 1234 becomes 12, a dot, and 34; 5 becomes 0.05. Converting through a double and formatting it would invite rounding errors and the wrong number of decimals.
  • The switch over Currency has no default, so the compiler warns (with -Wall) if a new currency is added to the enum and not here. The throw after the switch handles a value outside the enum, which C++ allows through a cast. The direct-call version used a chain of ?: instead, which gets no warning: a new currency would silently be sent as 826, pounds.
  • The translations are free functions in their own namespace, so the tests can check each mapping directly. The trade-off: they are visible to the rest of the shop, which must not use them. Keeping them in an unnamed namespace inside the .cpp would hide them, and the tests would then check them only through charge.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

checkout.hpp
// Charges the order through whatever gateway it is given, and returns a
// message for the customer. The gateway is passed by reference and used
// only during the call; PaymentGateway& accepts any class derived from
// it, which is what lets the tests pass a fake.
std::string pay_for_order(const ChargeRequest& request, PaymentGateway& gateway);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

checkout.cpp
// The client: it only turns a ChargeResult into words for the customer.
// It sees no vendor type, code, or exception. Any exception from charge
// (such as std::invalid_argument for a zero amount) passes through to
// the caller.
std::string pay_for_order(const ChargeRequest& request, PaymentGateway& gateway) {
// A virtual call: through the PaymentGateway&, this runs the charge of
// whichever gateway was passed in, OldPayGateway in main or a fake in
// the tests.
const ChargeResult result = gateway.charge(request);
const std::string order = "order " + request.order_id + ": ";
// One case per ChargeStatus, with no `default`, so the compiler warns
// if a status is added and not handled here.
switch (result.status) {
case ChargeStatus::approved:
return order + "paid " + display_amount(request.amount_cents, request.currency) +
", reference " + result.reference;
case ChargeStatus::declined:
return order + "declined (" + result.reason + ")";
case ChargeStatus::try_again_later:
return order + "not charged yet, will retry (" + result.reason + ")";
}
// Reached only by a status outside the enum (possible with a cast);
// without it, the function could end without returning a value.
return order + "unknown result";
}

pay_for_order now has one job: turn the result into words for the customer. It does not include any OldPay header.

class ChargeRequest

a struct: the shop's terms

Data members

  • std::string order_id;
  • std::string card_token;
  • std::int64_t amount_cents = 0;
  • Currency currency = Currency::eur;

class ChargeResult

a struct: the shop's terms

Data members

  • ChargeStatus status; approved, declined, or try_again_later
  • std::string reference; set when approved
  • std::string reason; set when not approved

interface (abstract class) PaymentGateway

Member functions

  • virtual ChargeResult charge(const ChargeRequest& request) = 0;

class OldPayGateway final

the adapter

Data members

  • oldpay::Terminal* terminal_; borrowed; must outlive the adapter

Member functions

  • explicit OldPayGateway(oldpay::Terminal& terminal);
  • ChargeResult charge(const ChargeRequest& request) override; translate, call, translate back

namespace global

not a real namespace: free functions at file scope

Functions

  • std::string pay_for_order(const ChargeRequest& request, PaymentGateway& gateway); the client
The shop's types and interface, the client, and the adapter

The outline leaves out the oldpay_conversions functions shown above, display_amount, which formats 12.34 EUR for messages, and the defaulted operator== on ChargeResult that the tests use.

  • The adapter borrows the terminal. main owns the oldpay::Terminal and creates it before the adapter, so it is destroyed after the adapter, as the rule requires. The adapter stores a pointer, and the constructor takes a non-const reference, so a temporary cannot be passed: in a scratch program, OldPayGateway gateway{oldpay::Terminal{"x"}}; was rejected by both GCC and Clang.
  • The adapter could own the terminal instead, as a data member created from a merchant id. That is simpler when nothing else uses the terminal. Borrowing is used here because tests read the stub’s log after the charge, and because a real terminal is often shared by several parts of a program.
  • Everything else is a value. Requests and results are plain structs, passed and returned by value or const&. The adapter keeps no state between calls.
  • Threads: the adapter adds no shared state of its own, so it is exactly as safe to call from several threads as the Terminal it wraps. This stub is not: its log and reference counter are plain members.
Charging order A-1001: the checkout speaks the shop's terms, the adapter translates both ways
Text description of the diagram

pay_for_order calls charge on OldPayGateway with order A-1001, token tok_ok, 1234 cents, and euros. The adapter converts 1234 cents to the text 12.34 and euros to 978, then calls authorize on the vendor’s Terminal with tok_ok, “12.34”, and 978. The Terminal returns a Response with code 0 and reference OP-000001. The adapter converts code 0 to approved, keeping the reference, and returns a ChargeResult to pay_for_order, which builds the message “paid 12.34 EUR, reference OP-000001”.

Diagram source (Mermaid)
sequenceDiagram
participant C as pay_for_order
participant A as OldPayGateway
participant T as oldpay Terminal
C->>A: charge(A-1001, tok_ok, 1234 cents, eur)
A->>A: 1234 to "12.34", eur to 978
A->>T: authorize(tok_ok, "12.34", 978)
T-->>A: Response, code 0, reference OP-000001
A->>A: code 0 to approved, with the reference
A-->>C: ChargeResult approved, OP-000001
C->>C: message "paid 12.34 EUR, reference OP-000001"

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The same three orders, through the adapter. main is the one place
// that knows both sides: it creates the vendor's Terminal, wraps it in
// an OldPayGateway, and hands the checkout only the gateway. The
// terminal is declared first, so it is destroyed after the gateway
// that borrows it (local objects are destroyed in reverse order).
oldpay::Terminal terminal{"shop-42"};
OldPayGateway gateway{terminal};
for (const ChargeRequest& order : orders) {
std::cout << pay_for_order(order, gateway) << '\n';
}
Expected output
before: order A-1001: paid 12.34 EUR, reference OP-000001
before: order A-1002: declined (card expired)
before: order A-1003: not charged yet, will retry (payment service unreachable: no route to the payment host)
order A-1001: paid 12.34 EUR, reference OP-000001
order A-1002: declined (card expired)
order A-1003: not charged yet, will retry (payment service unreachable: no route to the payment host)

Read the output against the requirements:

  • The three orders are paid, declined with a reason, and “not charged yet” (FR-1), through OldPay’s library (FR-2). Apart from the before: prefix, the first three lines, from the direct-call version, match the last three, so the adapter changed no results. (Each version uses its own new terminal, so the references match too.)
  • The third order’s token makes the stub throw LinkDown. The adapter turned it into a result, so pay_for_order did not need a try.

The tests check the checkout with a fake gateway, in the shop’s terms only (FR-3):

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_payments.cpp
// A fake gateway: the test chooses the answer, in the shop's terms. It is
// a second implementation of PaymentGateway, so pay_for_order accepts it
// exactly as it accepts OldPayGateway, and no vendor code is involved.
class FakeGateway final : public PaymentGateway {
public:
// `answer` is taken by value, then moved into the member: the strings
// inside are handed over, not copied a second time.
explicit FakeGateway(ChargeResult answer) : answer_{std::move(answer)} {}
// The request has no name, because the fake ignores it: whatever is
// asked, it counts the call and returns a copy of the chosen answer.
ChargeResult charge(const ChargeRequest&) override {
++calls;
return answer_;
}
int calls = 0; // public, so a test can check how often charge ran
private:
ChargeResult answer_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_payments.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) does the same
// for two values that should be equal, and prints both; and
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// that type of exception. They come from the site's test header,
// lld_test.hpp.
// static_assert is checked by the compiler, not when the tests run: if
// either condition were false, this file would not compile at all.
// is_abstract_v: PaymentGateway has a pure virtual function, so it
// cannot be created on its own.
static_assert(std::is_abstract_v<PaymentGateway>);
static_assert(!std::is_copy_assignable_v<PaymentGateway>); // protected operator=
// One order shared by the checkout tests. The token "any" means nothing
// to anyone: with a fake gateway, no vendor ever reads it.
const ChargeRequest order{"T-1", "any", 1234, Currency::eur};
// The checkout on its own, with a fake gateway for each of the three
// outcomes. It proves each status becomes the right customer message,
// with no vendor library, token, or code in the test.
LLD_TEST(the_checkout_reports_each_result_in_its_own_words) {
// The inner braces build the ChargeResult the fake will return:
// status, reference, reason.
FakeGateway paid{{ChargeStatus::approved, "R-9", ""}};
LLD_CHECK_EQ(pay_for_order(order, paid),
std::string{"order T-1: paid 12.34 EUR, reference R-9"});
FakeGateway declined{{ChargeStatus::declined, "", "card expired"}};
LLD_CHECK_EQ(pay_for_order(order, declined), std::string{"order T-1: declined (card expired)"});
FakeGateway later{{ChargeStatus::try_again_later, "", "busy"}};
LLD_CHECK_EQ(pay_for_order(order, later),
std::string{"order T-1: not charged yet, will retry (busy)"});
// pay_for_order called charge exactly once: it does not retry by itself.
LLD_CHECK_EQ(later.calls, 1);
}
// From here on, the adapter on its own, against the vendor stub. This one
// charges three orders, then reads the stub's log to see exactly what
// the adapter sent: amounts with two decimals (including a leading zero
// for 5 cents) and the right currency numbers. The results of charge are
// not needed, so they are not stored.
LLD_TEST(the_adapter_converts_amounts_and_currencies) {
oldpay::Terminal terminal{"test"};
OldPayGateway gateway{terminal};
gateway.charge({"T-1", "tok_ok", 1234, Currency::eur});
gateway.charge({"T-2", "tok_ok", 5, Currency::usd});
gateway.charge({"T-3", "tok_ok", 100000, Currency::gbp});
LLD_CHECK_EQ(terminal.log.size(), std::size_t{3});
LLD_CHECK_EQ(terminal.log[0], std::string{"12.34 978"});
LLD_CHECK_EQ(terminal.log[1], std::string{"0.05 840"});
LLD_CHECK_EQ(terminal.log[2], std::string{"1000.00 826"});
}
// Calls from_vendor directly with each code the adapter knows, plus one it
// does not (14), and compares the whole ChargeResult with ==. The extra
// brackets around each ChargeResult{...} keep its commas from being read
// as separate arguments to the LLD_CHECK macro.
LLD_TEST(the_adapter_maps_every_vendor_code) {
// Brings in just this one name, so the checks can say from_vendor.
using oldpay_conversions::from_vendor;
LLD_CHECK(from_vendor({0, "OP-1"}) == (ChargeResult{ChargeStatus::approved, "OP-1", ""}));
LLD_CHECK(from_vendor({51, ""}) ==
(ChargeResult{ChargeStatus::declined, "", "insufficient funds"}));
LLD_CHECK(from_vendor({54, ""}) == (ChargeResult{ChargeStatus::declined, "", "card expired"}));
LLD_CHECK(from_vendor({91, ""}) ==
(ChargeResult{ChargeStatus::try_again_later, "", "card issuer unavailable"}));
LLD_CHECK(from_vendor({14, ""}) ==
(ChargeResult{ChargeStatus::declined, "",
"declined by the payment service, code 14"}));
}
// tok_offline makes the stub throw oldpay::LinkDown. The test proves charge
// returns normally instead (if the exception escaped, the test would fail),
// with try_again_later and the vendor's detail kept in the reason.
LLD_TEST(the_vendors_exception_does_not_escape_the_adapter) {
oldpay::Terminal terminal{"test"};
OldPayGateway gateway{terminal};
const ChargeResult result = gateway.charge({"T-1", "tok_offline", 1000, Currency::eur});
LLD_CHECK(result.status == ChargeStatus::try_again_later);
LLD_CHECK_EQ(result.reason,
std::string{"payment service unreachable: no route to the payment host"});
}
// A zero amount is the shop's mistake: charge throws std::invalid_argument,
// and the empty log proves the vendor was never called.
LLD_TEST(the_adapter_refuses_a_zero_amount_before_calling_the_vendor) {
oldpay::Terminal terminal{"test"};
OldPayGateway gateway{terminal};
LLD_CHECK_THROWS(gateway.charge({"T-1", "tok_ok", 0, Currency::eur}), std::invalid_argument);
LLD_CHECK(terminal.log.empty());
}
// 10'000'000 cents (the ' only separates digits for reading) is
// "100000.00", one digit more than OldPay's limit of 99999.99. The stub
// answers code 13, "invalid amount", which the adapter does not know, so
// it becomes a decline that keeps the code: an answer, not a lost error.
LLD_TEST(an_amount_too_large_for_the_vendor_is_declined_not_lost) {
oldpay::Terminal terminal{"test"};
OldPayGateway gateway{terminal};
const ChargeResult result = gateway.charge({"T-1", "tok_ok", 10'000'000, Currency::eur});
LLD_CHECK(result.status == ChargeStatus::declined);
LLD_CHECK_EQ(result.reason, std::string{"declined by the payment service, code 13"});
}
  • the_checkout_reports_each_result_in_its_own_words tests every message without the vendor’s library, tokens, or codes. Compare it with the before-test above.
  • The other tests check the adapter on its own: the amounts and currencies it sends (read from the stub’s log), every code it maps, the exception it translates, the zero amount it refuses before calling the vendor, and an amount larger than OldPay accepts, which comes back as a decline with the vendor’s code, not as a lost error.
  • The static_asserts check that PaymentGateway is abstract and cannot be copy-assigned through a reference.

The vendor is a stub. A real adapter would also deal with time-outs, duplicate charges when a request is retried (many payment services accept an idempotency key that makes a retry safe), and logging the vendor’s raw answer for support staff. Each of those belongs in the adapter if it is about the vendor’s terms, and in the shop’s code if it is a business rule, such as how many times to retry.

One case needs care in a real system. The stub’s LinkDown means the request never left the shop, so “not charged yet” is true. A connection that breaks after the request was sent has an unknown outcome: the card may already have been charged. Telling the customer “not charged yet” and retrying is then safe only with an idempotency key, or after asking the vendor what happened to that order.

Instead of holding the adaptee, an adapter can inherit from it:

// A class adapter: it IS a PaymentGateway (public inheritance) and is
// built ON a Terminal (private inheritance). Private means the Terminal
// part is an internal detail: outside code cannot call authorize on it,
// or treat an OldPayClassAdapter as a Terminal.
class OldPayClassAdapter final : public PaymentGateway, private oldpay::Terminal {
public:
// The adapter creates its own Terminal: the base class is constructed
// from the merchant id, which is moved in rather than copied. Nothing
// is borrowed, so there is no lifetime to manage, but also no way to
// adapt a Terminal that already exists.
explicit OldPayClassAdapter(std::string merchant_id)
: oldpay::Terminal{std::move(merchant_id)} {}
ChargeResult charge(const ChargeRequest& request) override {
using namespace oldpay_conversions;
// authorize is called as this object's own (inherited) function,
// with no pointer. The arguments are worked out before the call,
// so a zero amount still throws before the vendor is reached.
// Unlike OldPayGateway, there is no try: LinkDown would escape.
return from_vendor(authorize(request.card_token, to_vendor_amount(request.amount_cents),
to_vendor_currency(request.currency)));
}
};

This compiled and ran in a scratch program, but it is rarely the better choice in C++:

  • It adapts one exact class, created by the adapter. It cannot adapt a Terminal that already exists, or one shared with other code, or a subclass chosen at run time.
  • It can only be written if the adaptee is not final and has a usable constructor and destructor; some vendor classes are created only by a factory function.
  • Its advantages are small: it can override the adaptee’s virtual functions, if it has any, it can reach the adaptee’s protected members, and it saves one pointer.
  • It hides the adaptee completely, which has a cost here: tests could no longer read the stub’s log.

The private inheritance keeps the vendor’s functions out of the adapter’s public interface, which is the point of adapting. Public inheritance would let callers reach authorize directly. (The version above also leaves out the LinkDown handling, to stay short.)

Function adapters and standard library adaptors

Section titled “Function adapters and standard library adaptors”

When the target is a single function, the adapter can be a lambda. A caller that takes a std::function<ChargeResult(const ChargeRequest&)> can be given a lambda that converts the request, calls the vendor, and converts the answer, with no class at all. The standard library uses the same idea in several places:

  • std::stack, std::queue, and std::priority_queue are called container adaptors: they give a container such as std::deque or std::vector the narrower interface of a stack or a queue.
  • The C++20 range adaptors, such as std::views::transform and std::views::filter, present an existing range through a different view without copying it.
  • std::not_fn and std::mem_fn are true function adapters: the first turns a predicate into its opposite, the second lets a member function be called like a free function.
  • A class does the right job with the wrong interface, and you cannot or should not change it: a vendor library, a legacy module, another team’s component, or a C API.
  • At a system boundary, to keep an outside system’s units, codes, error style, and exceptions in one place. This is where adapters appear most in real programs.
  • When tests need a fake, and the class they would fake has no interface of its own. The adapter’s target interface is the seam.
  • When a second implementation is expected, such as a move to a second payment vendor. Then the target interface already exists, and the second vendor needs only its own adapter.
  • You own both sides. If the shop wrote the other class too, change its interface instead of wrapping it.
  • The interfaces already match, or nearly. A wrapper that only forwards each call unchanged adds a class and translates nothing. The cost of unnecessary abstraction covers forwarding layers.
  • You want to add behaviour, not change the interface, such as logging or retries around a gateway. That is a different pattern, Decorator, which keeps the same interface.
  • You want one simple entry point to a whole subsystem, not a translation of one class. That is Facade.
  • One more class, and one more call between the client and the work. For a boundary, that cost is small and paid once.
  • Translation can lose information. OldPay’s codes 12, 13, and 14 (in the stub: invalid transaction, invalid amount, and invalid card number) all become “declined”, with only the number to tell them apart. Decide on purpose what the shop needs to know, and keep the raw value somewhere a person can find it.
  • The mapping must follow the vendor. When the vendor adds or changes codes, the adapter changes. That is the point: it is the only place that changes.
  • Leaks are easy. One function in the target interface that takes or returns a vendor type, such as oldpay::Response, undoes the separation.
  • A target interface shaped like the vendor’s. If PaymentGateway had authorize(token, amount_text, currency_code), the adapter would forward calls and the vendor’s terms would still be everywhere. Design the target from what the shop needs.
  • Business rules in the adapter. How many times to retry, or what to tell the customer, are the shop’s decisions. An adapter that makes them must be rewritten, rules and all, for the next vendor.
  • catch (...) to “be safe”. It turns programming errors into “try again later”, and the bug is never seen.
  • Mapping the unknown to success. Any code the adapter does not recognise must be treated as a failure.
  • An adapter for every caller. One adapter per adaptee and target is enough; two copies of the same mapping will drift apart.
  • “OldPay’s new version renumbers its codes.” Only from_vendor and its test change. pay_for_order and its tests do not.
  • “Move some customers to a second vendor.” Write a second adapter for the new vendor’s interface. pay_for_order does not change, and main chooses which gateway to create. The exercise below does this.
  • “Refunds.” Add refund to PaymentGateway in the shop’s terms, then implement it in the adapter. The target grows from what the shop needs.
  • “Retry a temporary failure up to three times.” That is a business rule, so it does not go in the adapter. It belongs in the shop’s code, or in a class that wraps any PaymentGateway and retries, which is a Decorator.

Exercise: Adapt a second vendor

The shop will also take payments through NovaPay. Its library is newer, and different again:

// NovaPay's library, as the vendor ships it. The adapter may use it, but
// cannot change it.
namespace nova {
struct Payment {
std::int64_t amount_minor; // whole cents
std::string currency; // "EUR", "USD", "GBP"
std::string source; // the card token
};
struct Result {
std::optional<std::string> id; // set when the payment succeeded
std::string error; // otherwise: "insufficient_funds", "expired_card", "rate_limited", ...
};
class Client {
public:
explicit Client(std::string api_key);
Result create_payment(const Payment& payment); // throws std::system_error when offline
};
} // namespace nova

rate_limited means NovaPay is busy and the request can be repeated later.

  1. Write NovaPayGateway, an adapter from nova::Client to the shop’s PaymentGateway.
  2. What changes in pay_for_order and its tests?
  3. Compare the two adapters. Which differences between the vendors does each one hide?
Show the explained answer

1.

// The second adapter: the same target interface, a different adaptee. It
// borrows a nova::Client, exactly as OldPayGateway borrows a Terminal.
class NovaPayGateway final : public PaymentGateway {
public:
explicit NovaPayGateway(nova::Client& client) : client_{&client} {}
ChargeResult charge(const ChargeRequest& request) override {
// The shop's own rule, checked before the vendor is called.
if (request.amount_cents <= 0) {
throw std::invalid_argument{"a charge must be for more than zero"};
}
// Translate the request. NovaPay already uses whole cents, so the
// amount passes straight through; only the currency is converted.
// The braces fill Payment's fields in order: amount, currency, card.
const nova::Payment payment{request.amount_cents, currency_code(request.currency),
request.card_token};
nova::Result result; // declared outside the try, to be read after it
try {
result = client_->create_payment(payment);
} catch (const std::system_error&) {
// The one failure NovaPay documents, caught by type and turned
// into the shop's terms. Nothing else is caught.
return {ChargeStatus::try_again_later, "", "payment service unreachable"};
}
// Translate the answer. An optional converts to true when it holds
// a value, so this asks "did NovaPay give a payment id?"; *result.id
// reads the id itself.
if (result.id) {
return {ChargeStatus::approved, *result.id, ""};
}
if (result.error == "insufficient_funds") {
return {ChargeStatus::declined, "", "insufficient funds"};
}
if (result.error == "expired_card") {
return {ChargeStatus::declined, "", "card expired"};
}
if (result.error == "rate_limited") {
return {ChargeStatus::try_again_later, "", "payment service busy"};
}
// Any error the adapter does not know is a decline, never a payment,
// and keeps NovaPay's own words for support staff.
return {ChargeStatus::declined, "", "declined by the payment service: " + result.error};
}
private:
// Currency to NovaPay's letter code. Static: it needs no adapter
// object. No `default`, so the compiler warns about a missed currency.
static std::string currency_code(Currency currency) {
switch (currency) {
case Currency::eur:
return "EUR";
case Currency::usd:
return "USD";
case Currency::gbp:
return "GBP";
}
throw std::invalid_argument{"unknown currency"};
}
nova::Client* client_; // borrowed; must outlive the adapter
};

The same rules as OldPayGateway: refuse a zero amount before calling the vendor, catch only the failure the vendor documents (std::system_error here), treat an unknown error as a decline and keep its text, and never let a NovaPay type into the result. (This answer was compiled and run against a stub of the API above with GCC and Clang.)

2. Nothing. pay_for_order uses only PaymentGateway, and its tests use a fake. main decides which adapter to create for which customers.

3. NovaPay already uses whole cents, so there is no amount text to build; OldPayGateway hides the "12.34" format. NovaPay uses letter currency codes; OldPay uses numbers. NovaPay reports success with an optional id and failure with words; OldPay uses numbers for both. NovaPay signals “offline” with a standard exception; OldPay with its own type. OldPay’s only temporary code is about the card issuer; NovaPay’s rate_limited is about the service itself, and both become try_again_later. Each adapter hides its own vendor’s differences, and the shop’s code sees none of them.

  • Facade gives a whole subsystem one simpler interface; Adapter makes one existing interface fit another. See Facade.
  • Bridge separates an abstraction from its implementations, and is designed in from the start; Adapter fits together classes that already exist. See Bridge and Adapter vs Bridge.
  • Decorator wraps an object and keeps its interface, to add behaviour; Adapter wraps an object to change its interface. See Decorator.
  • Dependency inversion is why the target interface belongs to the shop. See the Dependency Inversion Principle.
  • Ports and adapters (also called hexagonal architecture) builds a whole application around this idea: the core defines interfaces, and adapters connect it to databases, networks, and user interfaces. A page is planned.
  • Adapter lets code use a class whose behaviour is right and whose interface is wrong, by putting a translating class between them.
  • The target interface belongs to the client, and is shaped by the client’s needs. The adapter implements it and calls the adaptee.
  • At a system boundary, the adapter translates units, codes, error reporting, and exceptions, and is the only code that knows the outside system’s terms.
  • In C++, prefer the object adapter: hold the adaptee (borrowed or owned, with the lifetime stated), implement the target, and keep business rules out.
  • Map unknown results to failure, catch only the vendor’s exceptions, and never let a vendor type into the target interface.