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

In C++ programming, we can pass objects to a function in a similar manner as passing regular arguments.

Example 1: C++ Pass Objects to Function

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

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.