Welcome to our deep dive into C++ Friend Function! In this tutorial, we'll learn about this powerful feature of C++ that allows functions from one class to access the private and protected members of another class.
A friend function is a non-member function that has access to the private and protected members of a class. Friend functions are declared within the class definition and are not members of the class. They are often used when it is necessary to perform operations that involve more than one class but cannot be performed using member functions alone.
Friend functions are useful when you want to:
To declare a friend function, use the friend keyword followed by the function declaration within the class definition. Here's a simple example:
#include <iostream>
class MyClass {
private:
int myPrivateVariable;
friend void printPrivate(MyClass);
public:
MyClass() { myPrivateVariable = 42; }
void setPrivate(int value) { myPrivateVariable = value; }
};
void printPrivate(MyClass obj) {
std::cout << "Private variable: " << obj.myPrivateVariable << std::endl;
}
int main() {
MyClass myObj;
printPrivate(myObj);
return 0;
}In this example, printPrivate is a friend function that can access the private member myPrivateVariable of MyClass.
A friend class is similar to a friend function, but it grants all the member functions of a class access to the private and protected members of another class. To declare a friend class, use the friend keyword followed by the class name within the class definition of another class.
What is a friend function in C++?
Stay tuned for more exciting lessons on C++ programming with CodeYourCraft! š