🤝 C++ Friend Function – Let Outsiders Peek In
Normally, private members of a class are hidden from the outside world. But what if you want to give special access to a non-member function or another class? That’s where friend functions come in! 🔐
🔍 What is a Friend Function?
A friend function is not a member of the class, but it can access private and protected members like a close friend with VIP access. 😎
🔧 Example: A Friend Who Can Peek
#include <iostream> using namespace std; class SecretBox { private: int secret = 42; public: friend void peekInside(SecretBox); // Declaring a friend }; void peekInside(SecretBox box) { cout << "Peeking inside... secret is: " << box.secret << endl; } int main() { SecretBox myBox; peekInside(myBox); // Accessing private data return 0; }
🔐 How to Declare a Friend
- Use the keyword
friend
inside the class - The function does not belong to the class, but it can access private data
- Definition of the function stays outside the class
👫 Friend Class (Yes, That Too!)
You can also make an entire class a friend of another. That means all its member functions can access private/protected members of the friend class.
🔧 Example: Friend Class
#include <iostream> using namespace std; class Engine; class Car { private: int speed = 180; public: friend class Engine; // Engine is now a friend }; class Engine { public: void showSpeed(Car c) { cout << "Accessing Car speed: " << c.speed << " km/h" << endl; } }; int main() { Car myCar; Engine v8; v8.showSpeed(myCar); return 0; }
📌 Summary
- Friend function can access private/protected data
- Use
friend
keyword inside the class - Friend functions are not class members
- You can also declare a whole friend class
Think of friend functions as “trustworthy outsiders” — not family, but close enough to see your secrets! 🧑🤝🧑🔍