0

In C++ tutorials I've noticed that functions who take as a parameter classes interchange between using the actual object (dog) and a reference to the object (&dog). Yet, both approaches appear to be working just fine. Is there any difference? And if there isn't, what approach is generally considered best?

class Dog {
public:
    void printDog() {
        std::cout << "DOG, \n";
    }
};

void executePrint(Dog dog) {
    dog.printDog();
}

void executePrint2(Dog &dog) {
    dog.printDog();
}

int main() {

    Dog dog;
    
    executePrint(dog);
    executePrint2(dog);
    
    return 0;
}
Riccardo Perego
  • 383
  • 1
  • 11
  • 1
    Polymorphism for parameters must be done through a pointer (including smart pointer), or reference. For non-polymorphic cases, it can be passed by value. Passing by value makes a copy. What's "best" depends on what needs to be done with the parameter. – Eljay Jul 19 '22 at 19:47
  • 2
    `executePrint` will receive a COPY of the `dog` object. `executePrint2` will receive a pointer to the existing object -- no copy. The difference is quite important. – Tim Roberts Jul 19 '22 at 19:48
  • As Tim said, the non-reference uses a copy. It is considered good practice to use a reference by default, since copying an object can get expensive when the object gets big, and it can get big through refactors even if it starts life small. Preference for reference is also often combined with `const` correctness. If there is no reason for the function to modify the object, do this ```C++ class Dog { public: void printDog() const { std::cout << "DOG, \n"; } }; void executePrint(const Dog& dog) { dog.printDog(); } ``` – Jesse Maurais Jul 19 '22 at 21:06

0 Answers0