In this tutorial we will see how to pass an object to a function as an argument and how to return an object from a function.
Pass object to a function
An object can be passed to a function just like we pass structure to a function. Here in class A we have a function disp()
in which we are passing the object of class A
. Similarly we can pass the object of another class to a function of different class.
#include <iostream> using namespace std; class A { public: int n=100; char ch='A'; void disp(A a){ cout<<a.n<<endl; cout<<a.ch<<endl; } }; int main() { A obj; obj.disp(obj); return 0; }
Output:
100 A
Return object from a function
In this example we have two functions, the function input()
returns the Student
object and disp()
takes Student
object as an argument.
#include <iostream> using namespace std; class Student { public: int stuId; int stuAge; string stuName; /* In this function we are returning the * Student object. */ Student input(int n, int a, string s){ Student obj; obj.stuId = n; obj.stuAge = a; obj.stuName = s; return obj; } /* In this function we are passing object * as an argument. */ void disp(Student obj){ cout<<"Name: "<<obj.stuName<<endl; cout<<"Id: "<<obj.stuId<<endl; cout<<"Age: "<<obj.stuAge<<endl; } }; int main() { Student s; s = s.input(1001, 29, "Negan"); s.disp(s); return 0; }
Output:
Name: Negan Id: 1001 Age: 29
Leave a Reply