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?
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With