static_cast and a pointer-by-reference

Started by
0 comments, last by SiCrane 16 years, 2 months ago
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!
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)

This topic is closed to new replies.

Advertisement