En este tutorial, aprenderemos a pasar objetos a una función y devolver un objeto desde una función en la programación C ++.
En la programación de C ++, podemos pasar objetos a una función de manera similar a como se pasan argumentos regulares.
Ejemplo 1: pasar objetos a la función de C ++
// C++ program to calculate the average marks of two students #include using namespace std; class Student ( public: double marks; // constructor to initialize marks Student(double m) ( marks = m; ) ); // function that has objects as parameters void calculateAverage(Student s1, Student s2) ( // calculate the average of marks of s1 and s2 double average = (s1.marks + s2.marks) / 2; cout << "Average Marks = " << average << endl; ) int main() ( Student student1(88.0), student2(56.0); // pass the objects as arguments calculateAverage(student1, student2); return 0; )
Salida
Puntuación media = 72
Aquí, hemos pasado dos Student
objetos student1 y student2 como argumentos a la calculateAverage()
función.

Ejemplo 2: Objeto de retorno de C ++ desde una función
#include 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; )
Salida
Marcas1 = 96,5 Marcas2 = 75

En este programa, hemos creado una función createStudent()
que devuelve un objeto de Student
clase.
Hemos llamado createStudent()
desde el main()
método.
// Call function student1 = createStudent();
Aquí, estamos almacenando el objeto devuelto por el createStudent()
método en student1.