How to pass and return object from C++ Functions?

In C++ programming, we can pass objects to a function in the same way as passing built-in data types.

Example 1: C++ Pass Objects to Function

// C++ program to calculate the average marks of two students

#include <iostream>
using namespace std;

class Student {

   public:
    double marks;

    // constructor to initialize marks
    Student(double m)
      : marks{m} {
    }
};

// function that has objects as parameters
double average_marks(Student s1, Student s2) {

    // return the average of marks of s1 and s2 
    return (s1.marks + s2.marks)/2 ;
}

int main() {
    Student student1(88.0), student2(56.0);

  // pass the objects as arguments
   cout << "Average Marks = " << average_marks(student1, student2) << "\n";

    return 0;
}

Output

Average Marks = 72

Here, we have passed two Student objects student1 and student2 as arguments to the calculateAverage() function.

C++ Pass Objects to Function
Pass objects to function in C++

Example 2: C++ Return Object from a Function

#include <iostream>
using namespace std;

class Student {
   public:
    double marks1, marks2;
};

// function that returns object of Student
Student createStudent() {
    Student student;

    // Initialize member variables of Student
    student.marks1 = 96.5;
    student.marks2 = 75.0;

    // print member variables of Student
    cout << "Marks 1 = " << student.marks1 << endl;
    cout << "Marks 2 = " << student.marks2 << endl;

    return student;
}

int main() {
    Student student1;

    // Call function
    student1 = createStudent();

    return 0;
}

Output

Marks1 = 96.5
Marks2 = 75
C++ Return Object from Function
Return object from function in C++

In this program, we have created a function createStudent() that returns an object of Student class.

We have called createStudent() from the main() method.

// Call function
student1 = createStudent();

Here, we are storing the object returned by the createStudent() method in the student1.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community