Max Frai
Max Frai

Reputation: 64276

Derived classes and smart pointers

class Object { /* */ };

and a few derived:

class Derived1 : public Object { /* */ };
class Derived2 : public Object { /* */ };

And I have a function which makes derived objects and returns pointer for Object;

Object *make()
{
   return new Derived1();
}

So, this way I have to wrap returned object by smart pointer, but what return type to use?

TYPE? make()
{
   return boost::shared_ptr<Derived1>(new Derived1());
}

Upvotes: 3

Views: 2340

Answers (3)

bcsanches
bcsanches

Reputation: 2372

you can use:

boost::shared_ptr<Object> make()
{
return boost::shared_ptr<Object>(new Derived1());
}

Upvotes: 7

CB Bailey
CB Bailey

Reputation: 791869

Logically, the natural transformation would be to boost::shared_ptr<Object> but if the function always returns a Derived1 then it would be better to return boost::shared_ptr<Derived1> so that clients can take advantage of the better static type information if they want to.

Why was it necessary for the original function to throw away static type information?

Upvotes: 4

Simone
Simone

Reputation: 11797

The answer is easy:

boost::shared_ptr<Object> make()
{
   return boost::shared_ptr<Derived1>(new Derived1());
}

as the smart pointer preserve the pointer property wrt type conversion.

Upvotes: 2

Related Questions