Is this the right way to return an object from a function?
Car getCar(string model, int year) {
Car c(model, year);
return c;
}
void displayCar(Car &car) {
cout << car.getModel() << ", " << car.getYear() << endl;
}
displayCar(getCar("Honda", 1999));
I’m getting an error, “taking address of temporary”. Should I use this way:
Car &getCar(string model, int year) {
Car c(model, year);
return c;
}
getCarreturns aCarby value, which is correct.You cannot pass that return value, which is a temporary object, into
displayCar, becausedisplayCartakes aCar&. You cannot bind a temporary to a non-const reference. You should changedisplayCarto take a const reference:Or, you can store the temporary in a local variable:
But, it’s better to have
displayCartake a const reference since it doesn’t modify the object.Do not return a reference to the local
Carvariable.