Dans ce tutoriel, nous allons apprendre à passer des objets à une fonction et à renvoyer un objet à partir d'une fonction en programmation C ++.
En programmation C ++, nous pouvons passer des objets à une fonction de la même manière que des arguments normaux.
Exemple 1: Passer des objets C ++ à une fonction
// 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; )
Production
Notes moyennes = 72
Ici, nous avons passé deux Student
objets student1 et student2 comme arguments à la calculateAverage()
fonction.

Exemple 2: objet de retour C ++ à partir d'une fonction
#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; )
Production
Marques1 = 96,5 Marques2 = 75

Dans ce programme, nous avons créé une fonction createStudent()
qui renvoie un objet de Student
classe.
Nous avons appelé createStudent()
de la main()
méthode.
// Call function student1 = createStudent();
Ici, nous stockons l'objet retourné par la createStudent()
méthode dans le fichier student1.