Object and Function in C++
Object and Function in C++
Pass and return object from C++ Functions
We can pass objects to a function in a same way as passing regular or normal arguments.
Pass Objects to Function in C++
An object can be passed to a function similar to pass structure to a function. Similarly we can pass the object of other class to a function of different class.
Program of Passing object to function C++
#include <iostream> using namespace std; class Student { public: double marks; Student(double m) { marks = m; } }; void calculateAverage(Student s1, Student s2) { double average = (s1.marks + s2.marks) / 2; cout << "Average Marks = " << average << endl; } int main() { Student student1(88.0), student2(56.0); calculateAverage(student1, student2); return 0; }
Output
Average Marks = 72
Return Object from a Function in C++
Program of return object from a function
#include <iostream> using namespace std; class Student { public: double marks1, marks2; }; 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; } int main() { Student student1; student1 = createStudent(); return 0; }
Output
Marks1 = 96.5 Marks2 = 75
Read more, Constructor in C++