I am looking to find the correct way to use this kind of code safely:
renderer->renderEntity(entityManager->getEntity("player"));
Entity EntityManager::getEntity(string entityName)
{
for (int index = 0; index < entityVector.size(); ++index)
{
if (entityVector[index].getName() == entityName)
{
return entityVector[index];
}
}
}
Where you want to get an object from a container within an instance of a class, and want to check it exists, so you aren't making a call on an object that doesn't exist.
I know I could alter the call to:
if (entityManager->getEntity("player" != nullptr)
{
renderer->renderEntity("player");
}
I would like to avoid the double call to check the object exists. I guess this may be more a design than a syntax problem. Could I build the error checking into the getEntity() function that contains the for loop? I am not sure since the return value is Entity, so an Entity object must be returned. (same if it is a pointer, this isn't the code in my project, just a similar example).