top of page
Writer's picturecompnomics

Objects as Function Arguments and Return Values in C++


Objects can be passed as arguments to functions and can also be returned as function values in C++. This provides a powerful and flexible way to work with objects and create modular, reusable code.


Passing Objects as Function Arguments

When you pass an object as an argument to a function, a copy of the object is created and passed to the function. This is known as pass by value. Alternatively, you can pass objects by reference using the & operator, which avoids creating a copy and allows the function to modify the original object.


Example:

#include <iostream>

using namespace std;

class Person {
public:
    string name;
    int age;

    Person(string name, int age) {
        this->name = name;
        this->age = age;
    }
};

void displayPerson(Person p) {
    cout << "Name: " << p.name << endl;
    cout << "Age: " << p.age << endl;
}

int main() {
    Person person1("Alice", 25);
    displayPerson(person1);

    return 0;
}

Output:

Name: Alice
Age: 25

Returning Objects from Functions

You can also return objects from functions. When a function returns an object, a copy of the object is created and returned to the caller.

Example:

#include <iostream>

using namespace std;

class Person {
public:
    string name;
    int age;

    Person(string name, int age) {
        this->name = name;
        this->age = age;
    }
};

Person createPerson(string name, int age) {
    return Person(name, age);
}

int main() {
    Person person2 = createPerson("Bob", 30);
    displayPerson(person2);

    return 0;
}

Output:

Name: Bob
Age: 30

Passing Objects by Reference

To avoid creating copies of objects when passing them as arguments, you can pass them by reference using the & operator. This allows the function to modify the original object.

Example:

void modifyPerson(Person& p) {
    p.age++;
}

Key Points

  • Objects can be passed as arguments to functions and returned from functions.

  • When passing objects by value, a copy of the object is created.

  • When passing objects by reference, the original object is modified.

  • Returning objects from functions can be useful for creating functions that return complex data structures.

  • Be mindful of copy constructors and destructors when working with objects in functions.


By understanding how to work with objects as function arguments and return values, you can write more efficient and flexible C++ code.

10 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page