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.
š” 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.
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.
š 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.
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.
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! šÆ š” š ā