|
|
|
|
|
by timr
5280 days ago
|
|
"Their polymorphic factory isn't returning "different types." They're both returning A." 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. |
|
I have a polymorphic type that should be copyable. Because of the limitations of C++ copy constructors and operators, my only option is to expose a virtual method (call it "copy"). The non-smelly semantics we want are such that if you call "copy" on an object, you get an identical copy of the same type. So if you call "copy" on a pointer of type A, you get an A. Call it on a B, you get a B.
The contract itself is polymorphic. It doesn't commit to returning any particular flavor of A.
We can implement this method if we return naked pointers. But if we want to be safe and return a smart pointer, we have to introduce dynamic casting or other worse smells.