|
|
|
|
|
by MatthewCampbell
5277 days ago
|
|
Their polymorphic factory isn't returning "different types." They're both returning A. The derived one is just returning a specific type of A. If the shared "makeOne" returned naked pointer types A* and B* rather than shared_ptr, then this would all work correctly, thanks to C++'s covariant return type support. Covariant return types are a powerful feature in a language that doesn't support other forms of return type polymorphism. shared_ptrs function so similarly to pointers that it can be surprising when they don't support this behavior. Surprise and capability mismatch with pointers are strikes against shared_ptr. But not sufficient ones to stop me from using them. |
|
No, they're not. One is returning a pointer to A, and the other is returning a pointer to B (which just happens to be a subclass of A). It matters, and just because you can do it with a naked pointer doesn't mean that you should. The problem you've described is a code smell.
If I hand you a pointer to B, you (client code) can do everything that is exposed by B. If I hand you a pointer to A, you can only do the set of things exposed by A. And that's a fundamentally different interface guarantee.