În acest tutorial, vom învăța să trecem obiecte către o funcție și să returnăm un obiect dintr-o funcție în programarea C ++.
În programarea C ++, putem trece obiecte către o funcție într-un mod similar cu trecerea argumentelor obișnuite.
Exemplul 1: C ++ Pass Objects to Function
// 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; )
Ieșire
Note medii = 72
Aici, am trecut două Student
obiecte student1 și student2 ca argumente pentru calculateAverage()
funcție.

Exemplul 2: C ++ returnează obiectul dintr-o funcție
#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; )
Ieșire
Mărci1 = 96,5 Mărci2 = 75

În acest program, am creat o funcție createStudent()
care returnează un obiect de Student
clasă.
Am apelat createStudent()
din main()
metodă.
// Call function student1 = createStudent();
Aici, stocăm obiectul returnat de createStudent()
metodă în student1.