How do I define friend functions and classes in C++?

C++, friend functions, friend classes, access control, object-oriented programming
Learn how to define and use friend functions and classes in C++ to grant access to private and protected members of a class.
// Example of friend functions and classes in C++ #include class Box { private: double width; public: Box(double w) : width(w) {} // Friend function friend void printWidth(Box box); // Friend class friend class BoxPrinter; }; // Definition of the friend function void printWidth(Box box) { std::cout << "Width of box: " << box.width << std::endl; } // Definition of the friend class class BoxPrinter { public: void print(Box box) { std::cout << "Width of box in BoxPrinter: " << box.width << std::endl; } }; int main() { Box box(10); printWidth(box); // Calls friend function BoxPrinter printer; printer.print(box); // Calls method of friend class return 0; }

C++ friend functions friend classes access control object-oriented programming