C++ Friend Member Function

beginner
22 min

C++ Friend Member Function

Welcome to a comprehensive guide on C++ Friend Member Function! In this lesson, we'll explore this powerful feature of C++ that allows functions from one class to access the private members of another class.

Let's start by understanding the importance of friend functions.

What are Friend Functions in C++?

šŸ’” Pro Tip: Friend functions are not members of any class but have the right to access the private and protected members of the class they are declared as friends.

Imagine a scenario where you want to write a function outside the class definition that needs to access the private members of the class. Here's where friend functions come into play.

cpp
class MyClass { private: int privateVar; friend void friendFunction(MyClass &obj); }; void friendFunction(MyClass &obj) { std::cout << "Private Variable Value: " << obj.privateVar << std::endl; }

In the above example, friendFunction has access to the private member privateVar of the MyClass class, even though it is not a member of the class.

Why use Friend Functions?

šŸ“ Note: Friend functions are useful when you want to perform operations involving multiple classes and need to access private members of one class from another class or a function outside the class definition.

Let's consider an example where we have a Person class and a Friend class. The Friend class needs to access the private members of the Person class.

cpp
class Person { private: std::string name; int age; friend class Friend; }; class Friend { public: void greet(Person &person) { std::cout << "Hello, " << person.name << "! You are " << person.age << " years old." << std::endl; } }; int main() { Person person; person.name = "John Doe"; person.age = 30; Friend friendObj; friendObj.greet(person); return 0; }

In the above example, the greet function of the Friend class can access the private members of the Person class, as it is declared as a friend of the Person class.

Quiz Time!

Quick Quiz
Question 1 of 1

Which of the following functions has the right to access the private members of a class it is declared as a friend?

That's it for our introduction to C++ Friend Member Functions! In the next lesson, we'll dive deeper into how to use friend functions effectively in your C++ projects.

Stay tuned and keep coding! šŸŽÆ šŸ’” šŸ“ āœ