Tutorial Study Image

Passing and Returning Objects in C++


May 26, 2023, Learn eTutorial
254

In this tutorial, you will master everything about how to pass and return objects from a function in the C++ language with the help of very simple examples. We will learn how to provide an object to a function as an argument as well as how to return an object from a function with the help of some examples.

How passing and returning objects are done in C++?

In C++, class objects can be passed as arguments and returned from a function in the same manner as other variables. No unique keyword or header file is necessary for this.

Objects can be passed to a function in the same way that ordinary arguments are passed in C++.

Passing an Object as an argument in C++

In order to pass an object as an argument, use the object name as the argument when calling the function, just like we do with other variables.

Syntax


function_name(object_name);
 

object to a function.

Similar to passing a structure to a function, we can also pass an object to a function. There is a function called disp() in class A that accepts a class A object as a parameter. The object of a different class can be passed to a function of a different class in a similar manner.

let us write a C++ program in order to understand how to Pass an object to a function.


#include <iostream>
using namespace std;
class A {
   public:
    int age = 10;
    char ch = 'A';

    // function  has objects asthe parameters
    void display(A &a) {

       cout << "Age = " << a.age << endl;
       cout << "Character = " << a.ch << endl;

    }
};
int main() {
    A obj;
    obj.display(obj);
    return 0;
}

 

Output:


Age = 10
Character = A

Example 2:

C++ program in order to determine the average age of two students.


#include <iostream>
using namespace std;
class Student {
   public:
    int age;

    // constructor in order to initialize age
    Student(int a) {
        age = a;
    }
};
// function which has the objects as the parameters
void calculateAverage(Student s1, Student s2) {
    // calculate  average age of s1 and s2 
    int average = (s1.age + s2.age) / 2;

   cout << "Average Age = " << average << endl;

}
int main() {
    Student student1(20), student2(30);
    // pass the objects as arguments
        calculateAverage(student1, student2);

    return 0;
}

 

Output:


Average Age = 25

The calculateAverage() function has been given two Student objects, student1, and student2, as arguments.

How to return an Object from a Function in C++?

Objects may be returned by a function as references or by value. When a function returns an object by value, a temporary object that contains the return value is generated inside the function. The calling function then assigns this value to another object.

Defining a function that will return an object by value needs the following syntax.


class_name function_name (parameter_list) {
 // body of the function
}
 

Example:

Take a look at this example in order to get a better understanding of the idea of a function returning an object by value.

A program in order to illustrate the idea of returning objects from a function.


#include<iostream.h>
class weight {
  int kilogram;
  int gram;
  public:
    void getdata ();
    void putdata ();
    void sum_weight (weight,weight) ;
    weight sum_weight (weight) ;
} ;
void weight :: getdata() {
  cout<<"/nKilograms:";
  cin>>kilogram;
  cout<<"Grams:";
  cin>>gram;
}
 void weight :: putdata () {
   cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
 }
 weight weight :: sum_weight(weight w2) {
  weight temp;
  temp.gram = gram + w2.gram;
  temp.kilogram=temp.gram/1000;
  temp.gram=temp.gram00;
  temp.kilogram+=kilogram+w2.kilogram;
  return(temp);
}
int main () {
  weight w1,w2 ,w3;
  cout<<"Please enter the weight in kilograms and grams\n";
  cout<<"\n Enter weight #1" ;
  w3 = w1.sum_weight (w2);
  w1.getdata();
  cout<<" \n Enter weight #2" ;
  w2.getdata();
  w3.sum_weight(wl,w2);
  cout<<"/n Weight #1 = ";
  w1.putdata();
  cout<<"Weight #2 = ";
  w2.putdata();
  cout<<"Total Weight Will Be = ";
  w3.putdata();
  return 0;
}

 

A temporary object temp is created within the function in order to hold the return values because the method's return type is the weight (an object of class weight). The function accesses these values as temp kilogram and temp gram. The object temp is allocated to the object w3 in main() when control returns to it.

The figure illustrates accessing member variables within the function as well as returning a result from a temporary object.

Passing and Returning Objects in C++

When an object is returned by reference, no new object is constructed; instead, the calling function receives a reference to an original object in the called function.

Defining a function that will return an object by reference has the following syntax:


class_name& function_name (parameter_list) {
  //body of the function
}
 

However, since a reference to local data refers to data inside the function, the local object (object declared inside the method) cannot be returned by the function with a reference to it. As a result, this reference points to nothing when the function ends and the local data is deleted.


weight& weight::sum_weight(weight& w2) {
  weight temp; //object local to function
  temp.gram=gram+w2.gram;
  temp.kilogram=temp.gram/1000;
  temp.gram=temp.gram00;
  temp.kilogram+=kilogram+w2.kilogram;
  return temp; //invalid
}
 

Consider the function sum weight (), which has been updated as illustrated in this code section, to understand this concept.

An attempt has been made to return the reference to an object of type weight in this code section (that is temp). It is not possible, though, because a reference to the object temp is only valid while it is being used by the function sum weight(). Therefore, returning the temporary object reference outside of the function results in a compile-time error.

Example

In this example, there are two functions: display() accepts the Student object as an argument, and input() will return the Student object. The static cast operator is used in order to print the void pointer's contents. It changes the pointer's data type from its original void* type to the appropriate data type for the address that the pointer is storing:

C++ programming shows how to Return an object to a Function


#include <iostream>
using namespace std;
class Student {
   public:
    int stId;
    int stAge;
    string stName;

    // In this function we returning the student object
    Student input(int n, int a, string s) {
        Student obj:
        obj.stId = n;
        obj.stAge = a;
        obj.stName = s;
        return obj;
    }
    // In this function we pass object as an argument
    void display(Student obj) {

       cout << "Name = " << onj.stName << endl;
       cout << "Id = " << onj.stId << endl;
       cout << "Age = " << onj.stAge << endl;
    }
};
int main() {
    Student s;
    s = s.input (2005, 50, Alice)
    s.display(s);
    return 0;
}

 

Output:


Name = Alice
Id = 2005
Age = 50