c++ friend class
A friend class in C++ is a class that has access to the private and protected members of another class. To define a friend class, follow these steps:
- Declare the friend class: Start by declaring the friend class within the class that it wants to access. This is done by including a friend declaration inside the class definition. For example:
class MyClass {
friend class FriendClass;
};
- Define the friend class: Next, define the friend class outside of the class that it wants to access. This is done by writing the class definition as usual. For example:
class FriendClass {
// Class definition
};
- Access private and protected members: Once the friend class is defined, it can access the private and protected members of the class that declared it as a friend. This means that the friend class can directly access and modify the private and protected members of the declaring class. For example:
class MyClass {
private:
int privateVar;
protected:
int protectedVar;
friend class FriendClass;
};
class FriendClass {
public:
void accessPrivateProtected(MyClass& obj) {
obj.privateVar = 10; // Access private member
obj.protectedVar = 20; // Access protected member
}
};
In the above example, the FriendClass
is declared as a friend of MyClass
. This allows FriendClass
to access the private member privateVar
and the protected member protectedVar
of MyClass
. The accessPrivateProtected
function demonstrates how the friend class can access and modify these members.
Remember that the friend relationship is not reciprocal - just because FriendClass
can access the private and protected members of MyClass
, it doesn't mean that MyClass
can access the private and protected members of FriendClass
.
That's it! You have successfully defined and used a friend class in C++. I hope this explanation helps!