Question

I have seen a lot of advice that it is better to do Type object; than

Type* object = new Type();

in C++ whenever possible—i.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 do

Type object = Implementation();

because what that means is

Type object;
object = Implementation();

which requires constructing object as a Type initially—but 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?

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top