This C++ program demonstrates the use of keyword friend in classes. The program creates two classes ‘X’ and ‘Y’ and declares one class as ‘friend’ in another. By declaring friend, we mean that the friend class ‘Y’ will gain access to all the data members of the class ‘X’. The member functions of the friend class ‘Y’ can now change the values of data member of objects of class ‘X’ when passed as parameters.
Here is the source code of the C++ program demonstrates the use of keyword friend in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Demonstrate the use of Keyword Friend
*/
#include <iostream>
class X {
private:
int j;
protected:
int k;
public:
X(int jj = 1, int kk = 2) : j(jj), k(kk) {}
friend class Y;
friend void fun();
};
class Y {
int l;
public:
Y(int ll = 0) : l(ll) {}
void change(const X& x);
void printValue()
{
std::cout << "Y::l = " << l << std::endl;
}
};
void Y::change(const X& x)
{
l = x.j;
std::cout << "Y::change() : Y::l is now X::j " << std::endl;
}
void fun()
{
X x;
std::cout << "fun::X::j = " << x.j << std::endl;
}
int main()
{
X x;
Y y;
y.printValue();
fun();
y.change(x);
y.printValue();
}
$ a.out Y::l = 0 fun::X::j = 1 Y::change() : Y::l is now X::j Y::l = 1
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Practice Programming MCQs
- Check Computer Science Books
- Check C++ Books
- Check Programming Books
- Apply for C++ Internship