Friends C Specific - Rybd04/2143-OOP GitHub Wiki

Definition

Friends (C++ Specific)

the friend keyword is used to grant specific functions or classes access to the private and protected members of another class.

Explanation

Imagine you have a toy with a lock on it. Normally, only you can open it, but if you let a friend borrow the key, they can open the toy whenever they need to.

Basic Code Example

#include <iostream>
using namespace std;

class Box {
private:
    int width;

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

    // Declare function as a friend of the Box class
    friend void printWidth(Box b);
};

// Friend function
void printWidth(Box b) {
    cout << "Width of box: " << b.width << endl;  // Accessing private member of Box
}

int main() {
    Box box(10);
    printWidth(box);  // Friend function accessing private data
    return 0;
}

Image

image

Additional Resources

https://www.geeksforgeeks.org/friend-class-function-cpp/ https://learn.microsoft.com/en-us/cpp/cpp/friend-cpp?view=msvc-170

⚠️ **GitHub.com Fallback** ⚠️