0

Possible Duplicate:
C++ return a “NULL” object if search result not found

I'm trying to return NULL on a certain condition but it won't let me, why not and how can i make it return a null value or 0?

struct Entity
{
    USHORT X;
    USHORT Y;
    UINT Serial;
    USHORT SpriteID;
    EntityType Type;
    Direction FacingDirection;
};

the function is:

Entity& GetEntityAt(int index)
                {
                    if (!GameObjects.empty())
                    {
                        lock_guard<mutex> lock(PadLock);
                        Entity& result = GameObjects[index];
                        return result;
                    }
                    return NULL; // <- this won't compile
                }
Community
  • 1
  • 1
Dean
  • 499
  • 6
  • 13
  • 34

3 Answers3

4

There is no such thing as a null reference in C++. Your choices include:

  • change your function to return a (smart) pointer.
  • create a dummy sentinel object (const Entity null_entity), and return a reference to that.
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • What about `boost::optional`? :o – chris Jan 11 '13 at 04:01
  • @chris: I'm not familiar with that. But that's why I hedged my bets and said "your choices include..." ;) – Oliver Charlesworth Jan 11 '13 at 04:01
  • Or throw an exception. Depends what the calling code expects. – Potatoswatter Jan 11 '13 at 04:02
  • @OliCharlesworth, I see, that part sounded a bit limiting to me. Anyway, `boost::optional` is like a nullable type. Either it's valid and has a value, or it's invalid. Though maybe more expressive, it allows for some of the same syntax as a smart pointer. – chris Jan 11 '13 at 04:03
3

References can't be NULL. You have to use pointers instead:

Entity* GetEntityAt(int index)
                {
                    if (!GameObjects.empty())
                    {
                        lock_guard<mutex> lock(PadLock);
                        return &GameObjects[index];
                    }
                    return NULL;
                }
Pubby
  • 51,882
  • 13
  • 139
  • 180
1

A reference IS the object it references. Since NULL is not an object, you cannot return NULL if the function returns an reference.

DWright
  • 9,258
  • 4
  • 36
  • 53