Passing objects to functions

When passing objects to functions, only the reference is copied, not the object itself. If the method has access to attributes of the object, it can change the object. This change is preserved after the method returns.

Code Example

This is a simple C++ program that defines a class Person with a public member variable name. The program also defines a function setName that takes a string n and a pointer to a Person object o and sets the name of the Person object pointed to by o to n.

In the main function, two objects of the class Person are created dynamically using the new operator, and the pointers to these objects are stored in the variables p1 and p2. The function setName is then called twice, once to set the name of the Person object pointed to by p1 to “John” and once to set the name of the Person object pointed to by p2 to “Tom”.

Finally, the values of the name member variables of the Person objects are printed to the console using the cout statement.

#include <iostream>
using namespace std;

class Person {
    public:
        string name;
};

void setName(string n, Person *o) {
    o->name = n;
}

int main() {
    Person *p1 = new Person();
    Person *p2 = new Person();

    setName("John", p1);
    setName("Tom", p2);
    cout << p1->name << endl;
    cout << p2->name << endl;

    return 0;
}
Output
John
Tom