Saturday, June 17, 2023

Friend Function in CPP

 

Friend Function

 

Data hiding is a fundamental concept in object-oriented programming, and it restricts the access of private members from outside the class.

 

Syntax:

 

 

 

class className {

    ... .. ...

    friend returnType functionName(arguments);

    ... .. ...

}

 

 

#include<iostream.h>

#include<conio.h>

class Matrix

{

   int a[3][3];

public:

   void getMatrix();

   void printMatrix();

   friend Matrix add(Matrix X,Matrix Y);

};

void Matrix::getMatrix()

{

   cout<<"Get Matrix elements one by one";

   for(int i=0;i<3;i++)

      for(int j=0;j<3;j++)

        cin>>a[i][j];

}

void Matrix::printMatrix()

{

   cout<<"Given Matrix is:\n";

   for(int i=0;i<3;i++)

   {

      for(int j=0;j<3;j++)

      {cout<<a[i][j]<<" ";}

      cout<<"\n";

   }

}

Matrix add(Matrix X,Matrix Y)

{

Matrix T;

cout<<"Addition of two matrices is \n";

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

T.a[i][j]=X.a[i][j]+Y.a[i][j];

return T;

}

void main()

{

   /*declares 3 object P,Q,R of type class Matrix*/

   Matrix P,Q,R;

   clrscr();

   P.getMatrix();

   Q.getMatrix();

   R=add(P,Q); /*alling friend add to add two matrices*/

   R.printMatrix(); /*for printing the result*/

   getch();

}

output





0 comments:

Post a Comment