Friend Functions and friend class in c++

Friend Function 

A friend function is a function that is not a member of a class but has special permission to access its private and protected members.


   
Sometimes, it is necessary to access private or protected data of a class from a function that does not belong to that class.
Instead of providing multiple public getter and setter functions, a friend function allows direct access, simplifying the design in certain cases.


#include <iostream>
using namespace std;

class Box {
private:
    double width;

public:
    Box(double w){

        width = w;
    }

    friend void displayWidth(Box b);
};

void displayWidth(Box b) {
    cout << "Width of the box: " << b.width << endl;
}

int main() {
    Box b1(10.5);
    displayWidth(b1);
    return 0;
}


and friend classs


A friend class is a class that has access to the private and protected members of another class.
This is useful when two classes are closely related and need to share private data.

Why use a friend class?
When two classes work together, and one class needs to directly access the internal details of another,
declaring it as a friend avoids the overhead of getter/setter methods.


#include <iostream>
using namespace std;
class Square {
private:
    double side;

public:
    Square(double s){

        side = s;
    }

    friend class Rectangle;
};

class Rectangle {
public:
    double calculateArea(Square s) {
        return s.side * s.side;
    }
};

int main() {
    Square sq(4.5);
    Rectangle rect;
    cout << "Area of the rectangle: " << rect.calculateArea(sq) << endl;
    return 0;
}

Comments

Popular posts from this blog

programs of oops in c++

Basic DSA programs in c++

C++ Exception Handling and file handling