As I understand it, to pass/return polymorphic objects you need to use a pointer or reference type to prevent slicing problems. However, to return objects from functions you cannot create on stack and return reference because the local object won't exist anymore. If you create on the heap and return reference/pointer- the caller has to manage the memory- not good.
With the above in mind, how would I write a function which returns a polymorphic type? What return mechanism/type would I use?
You would return a smart pointer that takes care of the memory management and makes the ownership clear:
#include <memory>
struct IFoo
{
virtual ~IFoo() {}
};
struct Foo1 : IFoo {};
struct Foo2 : IFoo {};
std::unique_ptr<IFoo> make_foo()
{
return std::unique_ptr<IFoo>{new Foo1()};
}
Note that C++14 has std::make_unique
, which allows you to do the above without having to call new
directly. See related question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With