Friends - heshawacooray/OOP-Heshawa GitHub Wiki
Definition: A friend function is a function that is not a member of a class but has access to its private and protected members. Friend functions can be declared inside a class and are used when external functions or other classes need special access to the class’s internals.
Example code:
#include <iostream>
using namespace std;
class Car {
private:
string brand;
public:
Car(string b) : brand(b) {}
friend void displayBrand(Car& c); // Friend function declaration
};
void displayBrand(Car& c) {
cout << "Car brand: " << c.brand << endl; // Accessing private member
}
int main() {
Car car("Toyota");
displayBrand(car); // Calling friend function
return 0;
}