c++functionclassinheritancepolymorphism

How to share functions between C++ classes when the member object they operate on is defined differently (stack vs heap)?


I have a situation where I have one class, A, which contains the same functions as class B, but A defines it's own object on the stack to perform functions on, whereas B obtains it's object externally.

The name of the object and syntax is the same for each function in both classes.

A (made up) example:

class A
{
private:
   int numbers[200];

public:
   A() {};

   int do_stuff()
   {
      return numbers[0] + numbers[1];
   }
};


class B
{
private:
   int *numbers;

public:
   A(int *num): numbers(num) {};

   int do_stuff()
   {
      return numbers[0] + numbers[1];
   }
};

Despite it being trivial example, you can see how it will get wasteful if there are 20 functions and each is a copy-paste of the other.

Please don't waste collective energy arguing as to why A is better than B or vice-versa, I'm aware what I'm trying to achieve and it's non-trivial, unlike the above.


Solution

  • You can achieve this with a template.

    #include <type_traits>
    
    template <typename T>
    class X {
     public:
      X() requires(!std::is_pointer_v<T>) = default;
      explicit X(T n) requires std::is_pointer_v<T>
          : numbers(n) {}
    
      int do_stuff() { return numbers[0] + numbers[1]; }
    
     private:
      T numbers;
    };
    
    using A = X<int[200]>;
    using B = X<int*>;
    
    int main() {
      int ar[2]{};
      A a;
      B b(ar);
    }