Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

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.

How to Pass and Return Objects in C++ Functions

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
How to Pass and Return Objects in C++ Functions

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

  1. Three Essential Stages of 3D Printing Explained
  2. How Manufacturers Gain Competitive Edge Through IT‑OT Convergence
  3. C# Classes & Objects: Foundations for Robust OOP
  4. Mastering C++ Functions: From Basics to Advanced Usage
  5. C++ Classes & Objects: A Practical Guide to Object‑Oriented Programming
  6. C++ Pointers and Arrays: Mastering the Relationship
  7. Installing Dev‑C++ on Windows: Step‑by‑Step Guide
  8. C++ Classes & Objects: A Practical Guide with Code Examples
  9. Comprehensive Guide to Date and Time in C++
  10. PLA+ vs. Regular PLA: Key Differences and Benefits Explained