`friend` — C++ Keyword
`friend` — C++ Keyword
The friend keyword in C++: grants a function or class access to private and protected members.
`friend` — C++ Keyword
The friend keyword in C++: grants a function or class access to private and protected members.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
friendGrants a specific function or class access to the private and protected members of the class declaring the friendship.
class Name {
friend return-type function-name(params);
friend class OtherClass;
};
#include <print>
class Vector2 {
double x_, y_;
public:
Vector2(double x, double y) : x_(x), y_(y) {}
// Friend function: accesses private x_, y_
friend double dot(const Vector2& a, const Vector2& b) {
return a.x_ * b.x_ + a.y_ * b.y_;
}
// Friend class
friend class Matrix2;
};
class Matrix2 {
public:
void inspect(const Vector2& v) const {
std::println("x={} y={}", v.x_, v.y_); // accesses private members
}
};
int main() {
Vector2 a{1, 0}, b{0, 1};
std::println("{}", dot(a, b)); // 0
Matrix2 m;
m.inspect(a); // x=1 y=0
}
private and providing narrow friend declarations only when genuinely needed.friendint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}