Friends - Tryhardtocarry/2143-oop GitHub Wiki
A friend function is a function that is not a member of a class but has access to its private and protected members.
It is declared inside the class using the friend` keyword.
Friend functions allow external functions to access private data without needing getter methods.
#include <iostream>
using namespace std;
class Car {
private:
string brand;
int speed;
public:
// Constructor
Car(string b, int s) {
brand = b;
speed = s;
}
// Declare friend function
friend void CarDetails(const Car &c);
};
// Friend function definition (can access private members)
void CarDetails(const Car &c) {
cout << "Car Brand: " << c.brand << ", Speed: " << c.speed << " mph" << endl;
}
int main() {
Car car1("dodge", 50);
Car car2("Honda", 70);
// Calling the friend function
CarDetails(car1);
CarDetails(car2);
return 0;
}