In Java, class instance variables and such returned objects are actually references/pointers. Since they are pointers, they can point to null. Primitive types such as int
on the other hand are not pointers. Since they aren't pointers, they cannot point to null. You cannot have int x = null;
.
In C++, class instance variables and such returned objects are not pointers. Like the Java primitives, they cannot point to null.
How to properly return null/empty object in C++?
If the type of the object has a value that represents null or empty, then simply return that value. Here is an example where that type is a pointer:
int* function()
{
return nullptr;
}
When a type has an empty value, such value can usually (but not necessarily) be created using value initialisation. Here is an example that returns an empty vector:
std::vector<int> function()
{
return {};
}
If the type doesn't have a representation for null or empty, then you cannot return a null or empty value that doesn't exist.
However, using type erasure techniques, it is possible to design a class that internally contains either a value of another type, or doesn't. Using a template, such class can be used to augment any type with an empty value. The standard library comes with such template: std::optional
.
As for your particular example, idiomatic solution in C++ is to return an iterator to the found element, and return an iterator to the (one past the) end of the range if nothing is found. Iterator is a generalisation of a pointer. Your example re-written in C++:
auto getGetByName(std::string_view name) {
auto first = std::begin(people);
auto last = std::end(people);
for (; first != last; ++first) {
if (*first == name) {
return first;
}
}
return last;
}
// later
auto it = getByName("Sam");
if (it == std::end(people)) { ...
}
Note that there is no need to write that function, since the C++ standard library provides implementation of linear search. Simply call:
auto it = std::ranges::find(people, "Sam");