Launch your tech mastery with us—your coding journey starts now!
Course Content
Introduction to C++ Programming
0/2
Control Flow Statements
Control flow statements in C++ allow the program to make decisions, repeat tasks, or jump to specific parts of code based on conditions. These statements give a program logical structure and control over the sequence of execution. Mastering control flow is essential for writing efficient and responsive programs. This section covers decision-making statements, looping constructs, and jump statements in detail with syntax and examples.
0/4
Functions in C++
Functions in C++ are blocks of reusable code designed to perform a specific task. They help break large programs into smaller, manageable pieces and improve readability, modularity, and reusability. Functions reduce code duplication by allowing programmers to call the same block of logic from multiple places. This modular approach also makes debugging easier and enhances program structure and clarity.
0/4
Modern C++ and Concurrency
0/2

Introduction

In C++, the friend keyword is used to grant a non-member function or class access to the private and protected members of another class. While it breaks the strict encapsulation principle, it offers controlled flexibility in special cases like operator overloading, inter-class communication, and non-member utility functions. A friend function is declared inside the class with the keyword friend but defined outside like a regular function. Similarly, a friend class can access private members of another class by being explicitly declared as a friend. Though powerful, improper usage of friend can lead to tight coupling and security issues.

 

Need and Use of Friend in C++

Friend functions and classes are useful when two or more classes need to share data internally or when a function (like an overloaded operator) must access private members of multiple classes. They allow external functions or entire classes to bypass access restrictions without compromising design when used correctly. This is especially helpful in operator overloading, inter-object calculations, and debugging utilities. The friend keyword must be explicitly declared in the class that grants access.

General Syntax:

class ClassName {

    friend returnType functionName(parameters);  // Friend function

    friend class FriendClassName;               // Friend class

};

 

Friend Function in C++

A friend function is a non-member function that can access the private and protected data of a class. Though not part of the class, it acts like a close helper. It is declared using the friend keyword inside the class, but the function itself is defined outside the class. It does not have a this pointer since it’s not a member of the class. Common uses include arithmetic operations between objects of different classes.

Example:

#include <iostream>

using namespace std;

class Box {

    private:

        int width;

    public:

        Box(int w) : width(w) {}

        friend void printWidth(Box b);

};

void printWidth(Box b) {

    cout << “Width is: ” << b.width << endl;

}

int main() {

    Box b1(100);

    printWidth(b1);

    return 0;

}

 

Friend Function with Multiple Classes

A friend function can be made a friend of multiple classes if it needs to access private data from all of them. This is useful in scenarios like adding two objects of different classes or implementing utility operations like comparisons. Each class must individually declare the function as a friend. This provides selective access to internal data.

Example:

class ClassA;

class ClassB;

void sum(ClassA, ClassB);  // Forward declaration

class ClassA {

    private:

        int a;

    public:

        ClassA(int x) : a(x) {}

        friend void sum(ClassA, ClassB);

};

class ClassB {

    private:

        int b;

    public:

        ClassB(int y) : b(y) {}

        friend void sum(ClassA, ClassB);

};

void sum(ClassA obj1, ClassB obj2) {

    cout << “Sum: ” << obj1.a + obj2.b << endl;

}

 

Friend Class in C++

A friend class is a class whose all member functions can access private and protected members of another class. This is declared using friend class ClassName;. It enables tight coupling between two classes, often used in data structures like linked lists or complex number calculations. However, it should be used with caution to avoid design rigidity.

Example:

class B; // Forward declaration

class A {

    private:

        int valA;

    public:

        A(int x) : valA(x) {}

        friend class B;  // B is a friend of A

};

class B {

    public:

        void showA(A obj) {

            cout << “Value from A: ” << obj.valA << endl;

        }

};

 

Friend Member Function

Instead of making an entire class a friend, you can make only a specific member function of another class a friend. This gives limited access and improves encapsulation while still solving the purpose. The function must be explicitly declared as a friend in the class where access is granted.

Example:

class ClassB; // Forward declaration

class ClassA {

    private:

        int data;

    public:

        ClassA(int x) : data(x) {}

        friend void ClassB::displayData(ClassA);  // Only this function is a friend

};

class ClassB {

    public:

        void displayData(ClassA obj) {

            cout << “Accessed Data: ” << obj.data << endl;

        }

};

 

Advantages of Friend Functions & Classes

  1. Controlled Access: Allows selected external functions or classes to access private data without compromising full encapsulation.
  2. Inter-Class Communication: Helps in operations that require data from multiple objects of different classes.
  3. Enhanced Operator Overloading: Simplifies complex operator overloading between different types.
  4. Improves Performance: Functions can directly access private members without the overhead of getters/setters.
  5. Code Reusability: Common friend functions can be used by multiple classes for shared operations.

 

Disadvantages / Limitations

  1. Breaks Encapsulation: By exposing internal members, friend functions compromise the core OOP principle of data hiding.
  2. Tight Coupling: Overusing friend relationships creates dependencies, making code harder to maintain.
  3. Reduced Flexibility: Once declared, friend functions and classes cannot be revoked dynamically.
  4. Debugging Complexity: Hidden access paths can make it hard to trace bugs or understand the code flow.
  5. Design Complexity: Can lead to poor object-oriented design if misused.