Passing Objects as Arguments – Object Oriented Programming (OOP) Passing Objects as Arguments Object Oriented Programming (OOP) Third Semester | Second year BSc.CSIT | Tribhuvan University (TU)

Passing Objects as Arguments
We can pass objects as arguments to a function like any other data type. This can be done by pass-by-value and a pass-by-reference. In pass-by-value, a copy of the object is passed to the function and an modifications made to the object inside the function are not reflected in the object used to call the function. While, in pass –by-reference, an address of the object is passed to the function and any changes made to the object inside the function is reflected in the actual object. Furthermore, we can also return object from the function like any other data type. Consider the following C++ program for addition and multiplication of two square matrices which illustrates the above concepts.

```# include # define MAX_SIZE 10 int n; class Matrix { Int item[MAX_SIZE][MAX_SIZE]; public: void get_matrix(void); void display_matrix(void); Matrix add(Matrix m);    // Matix object as argumentand as return: pass by value void mul(Matrix &mat, Matrix m); // Matrix object as argument: pass by reference and pass by value }; void Matrix: :get_matrix(void) { cout<< “\n Enter the order of square matrix(nXn):” <<endl; cin>> n; cout<< “\n Enter the element of matrix: “ <<endl; for (int i=0; i<n; i++) For(int j=0; j<n; j++) cin>> item[i][j]; } void Matrix::display_matrix(void) { cout<< “\n The element of matrix is : “ <<endl; for (int i=0; i<n; i++) { for(int j=0; j<n; j++) cout<< item[i][j] << “\t”; cout<<endl; } } Matrix Matrix::add(Matrix m) { Matrix temp;          // object temp of Matrix class for(int i=0; i<n; i++) for(int i=0; i<n; i++) temp.item[i][j] = temp[i][j] + m.item[i][j]; return (temp);        // return matrix object } void Matrix::mul(Matrix &m, Matrix m) { for (int i=0; i<n; i++) for (int j=0; j<n; j++) { rm.item[i][j]=0; for (int k=0; k<n; k++) rm.item[i][j]=rm.item[i][j] + item[i][j]*m.item[k][j]; } } void main() { Matrix X,Y,Result; cout<<”Matrix X:”<<endl; X.get_matrix(); cout<<”Matrix Y:”<<endl; Y.get_matrix(); cout<<”\nAddition of X and Y:”<<endl; Result=X.add(Y); Result.display_matrix(); cout<<”\nMultiplication of X and Y:”<<endl; X.mul(Result,Y); //result=X*Y Result.display_matrix(); }```
If you look at the above program, you can observe that in main(), the statement