Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the non-pointer equivalent of NULL?

Tags:

c++

null

Apologies for my improper terminology.

I have a piece of code that returns a NULL pointer if an entry doesn't exist:

ObjectType * MyClass::FindObjectType( const char * objectTypeName )
{
    if ( objectTypeMap.find( objectTypeName ) == objectTypeMap.end() )
    {
        Msg( "\n[C++ ERROR] No object type: %s", objectTypeName );
        return NULL;
    }
    else
        return &objectTypeMap[ objectTypeName ];
}

I want to do the same thing but this time returning an object instead of just a pointer. The following code isn't giving me any compiler errors (which surprises me):

ObjectType MyClass::FindObjectType( const char * objectTypeName )
{
    if ( objectTypeMap.find( objectTypeName ) == objectTypeMap.end() )
    {
        Msg( "\n[C++ ERROR] No object type: %s", objectTypeName );
    }
    else
        return objectTypeMap[ objectTypeName ];
}

With the pointer I can check if the entry wasn't found like so:

if ( FindObjectType( objectType ) == NULL )
    //Do something

How do I perform the equivalent check with the object being returned?

like image 572
Phlox Midas Avatar asked Jun 07 '12 10:06

Phlox Midas


1 Answers

There is no language-level equivalent for objects.

One option is to create a "sentinel" object that is guaranteed to compare unequal to any "real" object, and return that:

class ObjectType {
public:
    static const ObjectType null;

    bool operator==(const ObjectType &rhs) const { /* need an appropriate comparison test */ }

    ...
};

ObjectType ObjectType::null(/* something unique */);


...

ObjectType foo(const char *objectTypeName) {
    if (cond) {
        return objectTypeMap[objectTypeName];
    } else {
        return ObjectType::null;
    }
}


...

if (foo(objectType) == ObjectType::null) {
    std::cout << "Returned the null object\n";
}
like image 181
Oliver Charlesworth Avatar answered Oct 24 '22 03:10

Oliver Charlesworth