Adapter
An adapter translates one interface into another so existing code can talk to a type it was not written for. In C++ that is a wrapper class, a set of free functions, or a std::queue over a deque.
Detailed Explanation
You have a LegacyLog with writeLine(const char*) and a new subsystem that wants void log(std::string_view). You do not change LegacyLog (it is in another library, or ABI-frozen). You write class LogAdapter { LegacyLog* inner; void log(string_view s) { inner->writeLine(...); } };. Callers see the new interface. The old type stays.
That is the object adapter (has-a). A class adapter uses inheritance: class LogAdapter : public ILog, private LegacyLog. Multiple inheritance makes this possible in C++. Prefer composition; private inheritance is "implemented in terms of" and is harder to test.
The STL is full of adapters. std::stack and std::queue adapt a container to a narrower API. std::reverse_iterator adapts an iterator. std::back_inserter adapts push_back to an output iterator. std::function adapts any callable to one type.
C APIs are the other everyday case. A C library wants a function pointer plus void* userdata. Your adapter is a static thunk: void thunk(void* p) { static_cast<Handler*>(p)->onEvent(); }. The adapter bridges calling conventions and lifetimes. The void* must outlive the C callback registration.
Adapter versus decorator: an adapter changes the interface. A decorator keeps the interface and adds behaviour. Adapter versus facade: a facade simplifies a subsystem for a new client; an adapter makes an existing type match an existing target interface.
Keep adapters thin. If the wrapper grows business rules, it is no longer an adapter; it is a service that happens to call an old API.
Code Examples
#include <iostream>
#include <string>
#include <string_view>
struct LegacyLog {
void writeLine(const char* s) { std::cout << s << '\n'; }
};
class LogAdapter {
LegacyLog* inner_;
public:
explicit LogAdapter(LegacyLog& inner) : inner_(&inner) {}
void log(std::string_view s) {
std::string tmp(s); // C API wants a C string
inner_->writeLine(tmp.c_str());
}
};
int main() {
LegacyLog raw;
LogAdapter log(raw);
log.log("boot"); // prints: boot
}#include <deque>
#include <queue>
int main() {
std::queue<int> q; // adapter over deque
q.push(1);
q.pop();
}Common Gotchas
Lifetime of the adaptee
an adapter that stores a pointer must not outlive the `LegacyLog`. Store a `unique_ptr` if the adapter owns it.
Class adapters and `delete` through the target interface
give the target a virtual destructor.