How to use a shared pointer of a pure abstract class without using reset and new?
Instead of new Bar
write make_shared<Bar>
, as you are making Bar
, not Interf
.
Bar b;
innerInterf = make_shared<Bar>(b); // copy constructed? (no idea if that is what you want?)
innerInterf = make_shared<Bar>(); // calls Bar::Bar()
Because I see non-virtual destructors, you might want to research about when to use virtual destructors, and also about rule of 0/3/5, if you haven't already.
Anyway, nice question and good MCVE.
One of the limitations of an abstract class is that it cannot create its objects directly, instead pointing to subclass objects as base-class Pointers.To facilitate the use of polymorphism, we often need to define virtual functions in the base class.
In many cases, it is unreasonable for the base class itself to generate objects.For example, animal as a base class can be derived from tiger, finch and other subclasses, but the animal itself to generate objects is obviously unreasonable.
In order to solve the above problems, the concept of pure virtual Function is introduced, and the Function is defined as a pure virtual Function(method: virtual returnType Function()= 0;)..To make a derived class non-abstract, the compiler requires that pure virtual functions in the derived class be overloaded to achieve polymorphism.Classes that also contain pure virtual functions are called abstract classes and cannot generate objects.This is a good solution to the above two problems.
For example, in the drawing program, Shape as a base class can derive circles, rectangles, squares, trapezoids, etc. If I want the sum of areas, then I can use an array of Shape *, just call the derived class's area() function in turn.You can't define it as an array without an interface, because it could be a circle, it could be a square, and it could be a rectangle, and so on.