Sign in to follow this  
rikibee

static_cast and a pointer-by-reference

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this