The Adapter Pattern is a structural design pattern that allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces by wrapping an existing class with a new interface.

In this C++ code, there is a business rule that needs to display the result of the sum 2 + 3, so we create an interface “Adder” for that need, so we can decide later an implementation for it.

class Adder {
  public:
  virtual int execute(int a, int b) = 0;
};
 
void clientCode(Adder& adder){
  int a = 2, b = 3;
  int result = adder.execute(a, b);
  printf("%d + %d = %d", a, b, result);
}

Then we have the ArrayAccumulator class to work with, but it doesn’t comply with our interface. We need to adapt its interface for it, so it can be used as an Adder.

class ArrayAccumulator {
  public:
  int execute(int values[], int size) {
    int sum = 0;
    for(int i=0; i<size; i++)
      sum += values[i];
    return sum;
  }
 
  void unrelatedMethod(float x){
    return x * x;
  }
};

We can create the adapter using composition pattern, getting the ArrayAccumulator via dependency injection . then we supply the needed interface with our ArrayAccumulator method.

class ArrayAccumulatorAdder : public Adder {
  private:
  ArrayAccumulator &arrayAccumulator;
 
  public:
  ArrayAccumulatorAdder(ArrayAccumulator &arrayAccumulator):
    arrayAccumulator(arrayAccumulator) {}
 
  int execute(int a, int b) override {
    int values[2] = {a, b};
    return arrayAccumulator.execute(values, 2);
  }
};

Finally, we can run the client code, using the ArrayAccumulator as an adder through polymorphism.

int main() {
  ArrayAccumulator arrayAccumulator;
  ArrayAccumulatorAdder adder = ArrayAccumulatorAdder(arrayAccumulator);
  clientCode(adder);
  return 0;
}

Full code

#include <iostream>
 
class Adder {
  public:
  virtual int execute(int a, int b) = 0;
};
 
class ArrayAccumulator {
  public:
  int execute(int values[], int size) {
    int sum = 0;
    for(int i=0; i<size; i++)
      sum += values[i];
    return sum;
  }
};
 
class ArrayAccumulatorAdder : public Adder {
  private:
  ArrayAccumulator &arrayAccumulator;
 
  public:
  ArrayAccumulatorAdder(ArrayAccumulator &arrayAccumulator): 
    arrayAccumulator(arrayAccumulator) {}
 
  int execute(int a, int b) override {
    int values[2] = {a, b};
    return arrayAccumulator.execute(values, 2);
  }
 
  void unrelatedMethod(float x){
    printf("This is an unrelated method");
  }
};
 
void clientCode(Adder& adder){
  int a = 2, b = 3;
  int result = adder.execute(a, b);
  printf("%d + %d = %d", a, b, result);
}
 
int main() {
  ArrayAccumulator arrayAccumulator;
  ArrayAccumulatorAdder adder = ArrayAccumulatorAdder(arrayAccumulator);
  clientCode(adder);
  return 0;
}
Output
2 + 3 = 5