• Advertisement
Sign in to follow this  

static_cast and a pointer-by-reference

This topic is 3673 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I stumbled upon a problem that I could not explain. I want to know why static_cast does not work in this situation:
class ObjectBase
{
   virtual ~ObjectBase();
};

class Object : public ObjectBase
{
   virtual ~Object();
};

void ObjectBuilder::BuildObject(EObjectType eType, ObjectBase*& pObject)
{
   switch (EObjectType)
   {
      ...
      case OBJECT:
         pObject = new Object();
         break;
      ...
   }
}


// ........... somewhere  in the program ...........

Object* pMyObject = 0;

objectBuilder.BuildObject(OBJECT, static_cast<ObjectBase*>(pMyObject));

Note that this code is just to illustrate the problem. Why static_cast cannot work when the pointer is passed as a reference but works if it is passed by value? I am using VC 2005 if that matters. Also I guess doing the same thing in two steps would work?
ObjectBase* pMyObjectBase = 0;
objectBuilder.BuildObject(OBJECT, pMyObjectBase);
Object* pMyObject = static_cast<Object*>(pMyObjectBase);

I am far from being a c++ guru (that would be quite fun), but I love those little "how-did-you-know-that?" details in programming languages. Cheers!

Share this post


Link to post
Share on other sites
Advertisement
The result of static_cast to a pointer type is an rvalue. Rvalues cannot be bound to non-const references. You can perform the cast here with a reinterpret_cast to a reference type. Ex: reinterpret_cast<ObjectBase *&>(pMyObject)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement