Curriculum
Course: Complete C++ Programming Course
Login

Curriculum

Complete C++ Programming Course

Text lesson

Creating a Friend Class in C++

In this lesson, you will learn

  • Friend Class
  • Examples

 

Friend Class

  • You can declare and define the entire class as a friend of another class.
  • In C++, a friend class is a class whose member functions are granted special permission to access the private and protected members of another class.

    Syntax

    class B; // Forward declaration of class B
    
    class A {
    private:
        int dataA;
    
    public:
        friend class B;  // Class B is a friend of class A
                        // Can access all the private members of class A.
    };
    

     

    Example: Creating a Friend Class

    #include <iostream>
    
    class B; // Forward declaration of class B
    
    class A {
    private:
        int dataA;
    
    public:
        A(int a) : dataA(a) {}
    
        friend class B; // Class B is a friend of class A
    };
    
    class B {
    public:
        void DisplayAData(A& obj) {
            std::cout << "A's data: " << obj.dataA << std::endl;
        }
    };
    
    int main() {
        A objA(42);
        B objB;
        objB.DisplayAData(objA); // Access A's private data using a friend class
        return 0;
    }
    

    Output

    A's data: 42
    

    Explanation

    Here, class B is declared as a friend of class A, which allows class B to access the private member dataA of class A. This demonstrates how you can make an entire class a friend of another class.

     

    Example 2: Printing Student Result

    #include<iostream>
    using namespace std;
    
    // Forward declaration of class Report
    class Report;
    
    class Student {
    private:
        string name;
        int marks;
    public:
        // Constructor
        Student(string n, int m) : name(n), marks(m) {}
        // Declare Report as a friend class
        friend class Report;
    };
    
    class Report {
    public:
        void displayResult(Student s) {
            // Report can access private members of Student
            cout << "Student Name: " << s.name << endl;
            cout << "Marks Scored: " << s.marks << endl;
            if (s.marks >= 50)
                cout << "Result: Pass" << endl;
            else
                cout << "Result: Fail" << endl;
        }
    };
    
    int main() {
        Student s1("Amit", 72);
        Student s2("Riya", 45);
        Report r;
        r.displayResult(s1);
        cout << "---------------------" << endl;
        r.displayResult(s2);
        return 0;
    }
    
    
    
    

    Output:

    Student Name: Amit
    Marks Scored: 72
    Result: Pass
    ---------------------
    Student Name: Riya
    Marks Scored: 45
    Result: Fail
    
    
    

    Explanation

    1. Class Student

      • Contains private data members name and marks. Declares Report as a friend class, giving it permission to access private members.

    2. Class Report

      • Uses its displayResult() function to access the private data (name, marks) of Student.

    3. Main Function

      • Creates student objects and calls displayResult() using a Report object.

     

    Important Note!

    If class A is a friend of B, it is not necessarily the class B will a friend of A.

     

    Example 3: Bank & ATM using Friend Class in C++

    #include 
    using namespace std;
    
    class Bank {
    private:
        string accountHolder;
        int accountNumber;
        double balance;
    
    public:
        // Constructor
        Bank(string name, int accNo, double bal) {
            accountHolder = name;
            accountNumber = accNo;
            balance = bal;
        }
    
        // Declare ATM as a friend class
        friend class ATM;
    };
    
    class ATM {
    public:
        void checkBalance(Bank &b) {
            cout << "Account Holder: " << b.accountHolder << endl;
            cout << "Account Number: " << b.accountNumber << endl;
            cout << "Current Balance: " << b.balance << endl;
        }
    
        void withdrawMoney(Bank &b, double amount) {
            if (amount <= b.balance) {
                b.balance -= amount;
                cout << "Withdrawal of " << amount << " successful." << endl;
                cout << "Remaining Balance: " << b.balance << endl;
            } else {
                cout << "Insufficient Balance!" << endl;
            }
        }
    };
     
    int main() {
        Bank b1("Amit Kumar", 12345, 10000.50);
    
        ATM atm;
        atm.checkBalance(b1);
        cout << "-----------------" << endl;
        atm.withdrawMoney(b1, 3000);
        cout << "-----------------" << endl;
        atm.checkBalance(b1);
    
        return 0;
    }
    
    

    Output:

    Account Holder: Amit Kumar
    Account Number: 12345
    Current Balance: 10000.5
    -----------------
    Withdrawal of 3000 successful.
    Remaining Balance: 7000.5
    -----------------
    Account Holder: Amit Kumar
    Account Number: 12345
    Current Balance: 7000.5
    
    
    

    Explanation

    1. Class Bank

      • Contains private data: accountHolder, accountNumber, and balance. Declares ATM as a friend class, allowing ATM direct access to private members.

    2. Class ATM

      • Can access private data of Bank directly because of friendship. Provides functions checkBalance() and withdrawMoney().

    3. Main Function

      • Creates a Bank object with details. Uses an ATM object to access and manipulate private data securely.

    This real-life Bank & ATM example is exam-ready, because it clearly shows:

    • Data HidingBank keeps its data private.

    • Controlled Access → Only ATM (friend class) can access that data.

    • Real-life analogy → Just like an ATM machine interacts with the bank system.

     

    Example of Mutual Friendship (Both Classes Are Friends)

    Sometimes, two classes may need to access each other’s private data. This can be done by declaring them as friend classes of each other.

    Example: Library and Student System

    #include 
    using namespace std;
    
    class Student; // Forward declaration
    
    class Library {
    private:
        string bookTitle;
        int bookID;
    
    public:
        Library(string title, int id) : bookTitle(title), bookID(id) {}
    
        // Declare Student as friend class
        friend class Student;
    
        void displayStudent(Student &s); // Defined later
    };
    
    class Student {
    private:
        string name;
        int rollNo;
    
    public:
        Student(string n, int r) : name(n), rollNo(r) {}
    
        // Declare Library as friend class
        friend class Library;
    
        void displayBook(Library &l) {
            cout << "Student Name: " << name << endl;
            cout << "Roll No: " << rollNo << endl;
            cout << "Issued Book: " << l.bookTitle << " (ID: " << l.bookID << ")" << endl;
        }
    };
    
    void Library::displayStudent(Student &s) {
        cout << "Book Title: " << bookTitle << endl;
        cout << "Book ID: " << bookID << endl;
        cout << "Issued To: " << s.name << " (Roll No: " << s.rollNo << ")" << endl;
    }
    
    int main() {
        Library lib("C++ Programming", 101);
        Student stu("Amit Kumar", 12);
    
        cout << "--- Student accessing Book Info ---" << endl;
        stu.displayBook(lib);
    
        cout << "\n--- Library accessing Student Info ---" << endl;
        lib.displayStudent(stu);
    
        return 0;
    }
    
    
    
    

    Output:

    --- Student accessing Book Info ---
    Student Name: Amit Kumar
    Roll No: 12
    Issued Book: C++ Programming (ID: 101)
    
    --- Library accessing Student Info ---
    Book Title: C++ Programming
    Book ID: 101
    Issued To: Amit Kumar (Roll No: 12)
    
    
    

    Key Points:

    • Mutual Friendship → Both Library and Student are declared as friend classes.

    • Two-way Access → Each class can access the private data of the other.

    • Real-Life Analogy → Library issues books to students, and both keep track of each other.

     

     


     

    End of the lesson….enjoy learning.

     

     

    Student Ratings and Reviews

     

     

     

    There are no reviews yet. Be the first one to write one.

     

     

    Submit a Review