Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ return type for function producing polymorphic object?

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?

like image 830
user997112 Avatar asked Jul 07 '13 14:07

user997112


1 Answers

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.

like image 153
juanchopanza Avatar answered Nov 14 '22 16:11

juanchopanza