How to Pass and Return Objects in C++ Functions
How to Pass and Return Objects in C++ Functions
This tutorial explains how to pass objects to functions and return objects from functions in C++, with practical examples and best‑practice guidance.
Example 1: Passing Objects to a 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 takes Student objects as parameters
void calculateAverage(Student s1, Student s2) {
double average = (s1.marks + s2.marks) / 2.0;
cout << "Average Marks = " << average << endl;
}
int main() {
Student student1(88.0), student2(56.0);
calculateAverage(student1, student2);
return 0;
}
Output
Average Marks = 72
Here, we passed two Student objects student1 and student2 to calculateAverage() by value. Passing by value creates copies; if the object is large, consider passing by reference.

Example 2: Returning an Object from a Function
#include <iostream>
using namespace std;
class Student {
public:
double marks1, marks2;
};
// function that returns a Student object
Student createStudent() {
Student student;
student.marks1 = 96.5;
student.marks2 = 75.0;
cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;
return student; // NRVO optimizes the copy
}
int main() {
Student student1;
student1 = createStudent();
return 0;
}
Output
Marks 1 = 96.5 Marks 2 = 75

The function createStudent() constructs a Student instance, prints its values, and returns it. In main(), the returned object is assigned to student1. Modern compilers employ Return Value Optimization (RVO) to avoid unnecessary copies.
C Language
- Three Essential Stages of 3D Printing Explained
- How Manufacturers Gain Competitive Edge Through IT‑OT Convergence
- C# Classes & Objects: Foundations for Robust OOP
- Mastering C++ Functions: From Basics to Advanced Usage
- C++ Classes & Objects: A Practical Guide to Object‑Oriented Programming
- C++ Pointers and Arrays: Mastering the Relationship
- Installing Dev‑C++ on Windows: Step‑by‑Step Guide
- C++ Classes & Objects: A Practical Guide with Code Examples
- Comprehensive Guide to Date and Time in C++
- PLA+ vs. Regular PLA: Key Differences and Benefits Explained