1

What is the proper way to up-cast a child shared pointer to its parent shared pointer? The commented section where I'm going from an apple to a fruit, is where I'm unclear.

class Fruit
{
};

class Apple : public Fruit
{
};

typedef std::shared_ptr<Fruit> FruitPtr;
typedef std::shared_ptr<Apple> ApplePtr;

int main()
{
    ApplePtr pApple = ApplePtr( new Apple() );

    FruitPtr pFruit = /* what is the proper cast using c++ 14 */
}
pyInTheSky
  • 1,459
  • 1
  • 9
  • 24

2 Answers2

3

You can to use a std::static_pointer_cast, it does exactly what you want:

class Fruit { };
class Apple : public Fruit { };

int main() {
  std::shared_ptr<Apple> pApple = std::make_shared<Apple>();
  std::shared_ptr<Fruit> pFruit = std::static_pointer_cast<Fruit>(pApple)
  return 0;
}

On a side note, I'd avoid constructing a shared_ptr directly. The tradeoffs of doing that or using make_shared can be read on this cppreference.com page. I'd also avoid typedefining ApplePtr and FruitPtr as you did because it may be confusing to someone reading your code because there is no indication they are shared pointers instead of raw pointers.

Milos
  • 330
  • 1
  • 9
Leonardo
  • 1,834
  • 1
  • 17
  • 23
1

You can simply use implicit upcasting:

FruitPtr pFruit = pApple

If you will add breakpoints, you can notice that after this line the strong reference counter increases to 2 (which I assume is what you would like to have happened).

Unrelated comment: Prefer the usage of make_shared over calling new yourself (read Difference in make_shared and normal shared_ptr in C++ as to why)

Eylon
  • 51
  • 3