Q:

Ways to return an object in C++ method

Say I have a class that looks like this
class MyAnimals{
public:
    Animal getAnimal(int index){
        return animals.at(index);
    }
private:
    vector<Animal> animals;
}

From what I've learned about C++ so far, I think getAnimal currently returns a copy of the animal, not a reference like in Java. I've seen this suggested as the correct way to go about returning objects, but what if you want to modify that animal once it's returned? I'd just be changing the copy of it and the actual animal inside of MyAnimals.animals would remain unchanged. One way I've seen to get around this is to return Animal& instead of Animal, and that seems to work for the most part, but what if I want to reassign the variable the was assigned to that returned Animal? For example,
Animal& a = myanimals.getAnimal(1);
a = myanimals.getAnimal(2);

From what I get, this would change the animal at myanimals.animals[1] to be the same exact object as myanimals.animals[2], since a was a reference. What are the different ways to go about returning objects?

A:

From what I've learned about C++ so far, I think getAnimal currently returns a copy of the animal, not a reference like in Java.

Correct.

I've seen this suggested as the correct way to go about returning objects

If you intend to return a copy, then yes.

I'd just be changing the copy of it and the actual animal inside of MyAnimals.animals would remain unchanged.

Correct.

One way I've seen to get around this is to return Animal& instead of Animal, and that seems to work for the most part

Yes, references are exactly what you need for that.

but what if I want to reassign the variable the was assigned to that returned Animal?

Well, typically there is no need to do re-assign an existing reference  (which is not allowed anyway). Instead of what you did, you could do:
Animal& a = myanimals.getAnimal(1);
Animal& b = myanimals.getAnimal(2);

If you for some reason need to, then use a pointer instead, to get around the limitation. You can do this even when you return a reference:
Animal* a = &myanimals.getAnimal(1);
a = &myanimals.getAnimal(2);

