What is friend class? Explain with example.

Q.2) a) What is friend class? Explain with example.

Ans.

If object of one class wants to access the private data member and member function of other class then we can declare a class as friend class. C++ provides a keyword friend, by using this keyword you can declare a class or function as friend. Friend function or friend class should be used carefully because it hit the encapsulation concepts.

The syntax of creating a class as friend is as follows.

friend class class_Name
Important points regarding friend class.

- Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend of A automatically.
- Friendship is not inherited.

Example:
#include "conio.h"
#include "iostream.h"

classMyClass
{
int n; // private data member of MyClass
friend class YourClass;
//Now YourClass object can access the private and protected member of MyClass.
public:
voidgetData()
{
cout << "Enter the value of n";
cin >> n;
}
};

classYourClass
{
public:
voidshowData(MyClassobj)
{
cout << "value of n=> " << obj.n; // Accessing private data of MyClass
}
};

void main()
{
MyClassmyObj;
YourClassyourObj;
myObj.getData();
yourObj.showData(myObj);
}

b.) Write a program for bubble sort using templates.

Ans.

#include < conio.h>
#include < iostream.h>
template < class T>

class Sort
{
inti,j;
public:
voidbubbleSort(T a[],int n)
{
for(i=0;i {
for(j=i+1;j {
if(a[i]>a[j])
{
T temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
};
void main()
{

intn,i;
int *ptr;
char *charPtr;
Sort < int>intObj;
Sort < char>charObj;

cout << " \nEnter how many number you want to sort => ";
cin >> n;

ptr=new int(n);
cout << "\n Enter the " << n << " Element => ";
for(i=0;i {
cin >> ptr[i];
}

cout << "\n Enter how many character you want to sort =>";
cin >> n;
charPtr=new char(n);
cout << "\n Enter the " << n<< " Element => ";

for(i=0;i {
cin >> charPtr[i];
}

cout << "\n The sorted number are \n";
intObj.bubbleSort(ptr,n);

for(int i=0;i {
cout << ptr[i] << " ";
}

charObj.bubbleSort(charPtr,n);
cout << "\n The sorted charectars are \n";
for(int i=0;i {
cout << charPtr[i] << " ";
}
}
Post your comment