Should you use a wrapper class or inherit in order to extend a user’s class

  c++

Say I have a library that wants to extend the behaviour of an end user’s class.

Should I always use a wrapper class along the lines of:

template<typename T>
struct wrapper
{
  std::unique_ptr<T> wrapped_object;
  T* operator->() {return wrapped_object.get();}
  // other stuff
};

Or is it safe to inherit from the user’s class, i.e.:

template<typename T>
struct wrapper : public T
{
  wrapper(auto&&... args) : T{args...} {}
  // functionality
};

I seem to remember that the general advice is to always use a wrapper class in such cases, but would like to know why that is.
So if anyone could elaborate that would be much appreciated!

Source: Windows Questions C++

LEAVE A COMMENT