I have seen a lot of advice that it is better to do Type object; thanType* object = new Type();in C++ whenever possiblei.e., minimize your use of new. I understand the rational behind this and appreciate it.But according to my understanding, to practice dependency inversion requires pointers, e.g.:Type* object = new Implementation();where Type is abstract (i.e. contains at least one pure virtual method) and Implementation is concrete. It is not possible to doType object = Implementation();because what that means isType object;object = Implementation();which requires constructing object as a Type initiallybut that cannot be done, since Type is abstract.Is there an inherent tension between the dependency inversion principle and avoiding new when using C++? If so, what patterns/principles/practices can be used to mitigate this tension?
Tension between the dependency inversion principle and avoiding new in C++?
c++;memory;solid
You can absolutely use Dependency Injection without ever using new().  Polymorphism, which is what you're talking about here, is realized in C++ using pointers and/or references.  Doc Brown already addressed references, let's talk about pointers.As an example (assuming that Implementation is derived from Type, and Bar's constructor takes a pointer to a Type):Implementation imp;Bar bar(&imp);The address of operator (&) takes the address of an object, the result is a pointer to the object.  This is a different way of getting a pointer to an object (different compared to your use of new, that is.)In C++, any time I have a pointer to a Derived, I can also use it as a pointer to a Base.  That's the whole idea of polymorphism, a Derived is a Base, right?If my 2-step example above made a leap that you couldn't follow, I'll repeat it here, but with one more (unnecessary) step:Implementation imp;Type *t = &imp;Bar bar(t);t is a pointer to a Type, so it can point to any class derived from Type, including Implementation.  No use of new.  No tension.