Friend Class Example in C++


A My class has been defined with three data members - a (private), b (protected), and c (public). A Your class has been declared with a public member function fun. In the fun member function of the Your class, an object of the My class is created, and its private, protected, and public members are accessed.

This is possible because the Your class has been declared as a friend of the My class using the friend keyword. When the program is executed, it creates an object of the Your class and calls its fun member function. The fun function creates an object of the My class, sets its data members, and prints them to the console.

Source Code

#include <iostream>
//Friend Class
using namespace std;
class Your;
class My
{
private :
    int a;
protected :
    int b;
public:
    int c;
    friend Your;
};
class Your
{
public:
    void fun()
    {
        My t;
        t.a=10;
        t.b=20;
        t.c=30;
        cout<< "A : "<<t.a<<endl;
        cout<< "B : "<<t.b<<endl;
        cout<< "C : "<<t.c<<endl;
    }
};
int main()
{
    Your o;
    o.fun();
    return 0;
}
To download raw file Click Here

Output

A : 10
B : 20
C : 30

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples