Reputation: 23800
Imagine you are implementing a List Data Type in C++. This List of yours will keep items in a simple array and will hold instances of type: "Animal".
So for example, addItem method will be something like this:
void MyAnimalList::insertAnimal(Animal a){
animalArray[currentPosition] = a;
currentPosition++;
}
So we simply have a currentPosition in the our List implementation and when we add a new Animal to it, Animal a is now referenced in the animalArray in "currentPosition" and currentPosition is then increased.
My question will be about retrieveItem. Is there any difference between these 2:
void MyAnimalList::getTheLastAddedAnimal(Animal &a){
a = animalArray[currentPosition-1];
}
Animal MyAnimalList::getTheLastAddedAnimal(){
return animalArray[currentPosition-1];
}
Obviously, the second method will be called like:
Animal lastAddedAnimal = myAnimalList.getTheLastAddedAnimal();
and the first one should be called like:
Animal someAnimal;
myAnimalList.getTheLastAddedAnimal(someAnimal);
Upvotes: 0
Views: 62
Reputation: 258618
The difference is semantic. If a method is called getXXXXX
, you expect it to return that thing.
Most decent compilers implement NRVO, so efficiency isn't really an issue here. I'd go with the second version.
I would however change the definition of insertAnimal(Animal a)
to insertAnimal(const Animal& a)
.
Upvotes: 2