C++ friend Keyword
Example
A friend function can access the private attributes of a class:
class Person {
private:
int age;
public:
Person(int a) {
age = a;
}
friend void printAge(Person p);
};
void printAge(Person p) {
cout << "Age: " << p.age;
}
int main() {
Person myObj(30);
printAge(myObj); // OK
// cout << myObj.age; // Error, because age is private
return 0;
}
Definition and Usage
The friend keyword gives a function or another class access to the private and protected members of a class. The class decides who its friends are, with a friend declaration inside the class.
A friend function is not a member of the class. You call it like a normal function, like printAge(myObj), not with a dot.
To make a whole class a friend, write friend class and the name of the class, like friend class Car;.
Related Pages
Read more about friend functions in our C++ Friend Functions Tutorial.