boost:shared_ptr base class cast.

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • boost:shared_ptr base class cast.

      Hey,

      I'm starting to try out boosts smart pointers, and so far I love'em. :)
      But I have come to a problem that I have a hard time solving, and I might be blind, but I can't find any information about it, so I come her.

      The thing I try to do is to cast a class to one of it's childs.
      This is how it looks:
      SceneNodeBase -> RootNode (RootNode inherits from SceneNodeBase)

      The thing is that my scene graph manager got a function that's called

      Source Code

      1. typedef boost::shared_ptr<SceneNodeBase> SceneNodeBasePointer;
      2. typedef boost::shared_ptr<RootNode> RootNodePointer;
      3. SceneNodeBasePointer FindByName(const char *pName)


      When I want to find my root node, I type,

      Source Code

      1. RootNodePointer r = sgm->FindByName("root");


      The trouble here is that my compiler complains about...

      Source Code

      1. ...error C2440: 'initializing' : cannot convert from 'SceneNodeBase *const ' to 'RootNode *'


      I have found boost:static_pointer_cast() and boost:dynamic_pointer_cast(), but I can't figure out if they are right, or how I use them.

      Anyone here that could help me with this problem?

      Best regards
      Jesper, Sweden.
    • Originally posted by Turing
      Yes those are the function you'll need for downcasting.
      Because you know for sure that the function will return a RootNode it's safe to use a static_cast instead of a dynamic cast.


      Hello Turing,

      Would I step over the line if I asked for a simple example from you, on how this could look codewise?

      Best regards
      Jesper, Sweden
    • I think the compiler is complaining that you can't cast away the 'const' part.
      Mr.Mike
      Author, Programmer, Brewer, Patriot
    • I agree with Mike on that one. However, here's a simple example of using static_pointer_cast that's in our game:

      Note:
      process_pointer is of type ProcessSharedPtr. I'm returning an EntityComponentControllerWeakPtr (heh, yeah, it's a mouth full. VAX rocks), which derives from Process.

      Source Code

      1. return boost::static_pointer_cast<EntityComponentController>(process_pointer);


      Another example is this:

      Source Code

      1. class A
      2. {
      3. //...
      4. };
      5. class B : public class A
      6. {
      7. //...
      8. };
      9. boost::shared_ptr<A> ptr_to_a(new A);
      10. boost::shared_ptr<B> ptr_to_b = boost::static_pointer_cast<B>(ptr_to_a);
      Display All


      Hope that helps.
      Feel you safe and secure in the protection of your pants . . . but one day, one day there shall be a No Pants Day and that shall be the harbinger of your undoing . . .