Is it possible to initialize a variable from a return parameter (by ref)? Say I have something like:
Car c; // <- don't want to create a new Car here!
if (findCar("beetle", c)) {
...
}
where if findCar succeeds, it returns true and fills c:
bool findCar(string name, Car& out) {
...
// return true if found
out = thecar;
return true;
}
Now, my class Car doesn’t have a 0-argument constructor, so the above code fails to compile. Is there a way to keep c uninitialized until the call to findCar?
Solutions I thought of are:
- adding a cheap 0-argument constructor to Car
- switch to pointers (which I’d rather avoid)
Sort of. The problem is that a reference absolutely must refer to an actual object. So, if you return by reference then someone must create an object for that returned reference. Therefore if you can’t find a matching object, it’s not really meaningful to return a reference. If you pass a reference in, then you must create an object first, for the argument to refer to.
You could work around this for example as follows:
Caller does:
or
Car &c = findCar("beetle");if they want to “see” the actual object found rather than a copy of it. IffindCarwants callers to only ever see a copy, not some internal object, then of course you can return by value rather than by reference – the difference is one&in the function signature.And someone somewhere has to handle the exception.
If you’d prefer to avoid exceptions then the right thing to return from a
findfunction is a pointer (or other iterator). It’s what the standard containers and algorithms do when searching, and there are special values (end iterators, or you could use null pointers) that mean “not found”.