Friends - EduardoMSU/OOP-2143 GitHub Wiki
Friends in Object-Oriented Programming (OOP)
What Are Friends?
In C++, friends are special functions or classes that are allowed to access the private and protected members of another class. Typically, these functions or classes are not members of the class but are granted access to its internal details for specific purposes, such as performing tasks that require intimate knowledge of the class.
Key Characteristics of Friends
Characteristic | Description |
---|---|
Access to Private/Protected | Friends can access private and protected members of a class, unlike non-friend functions. |
Not Members of the Class | Friend functions or classes are not part of the class and do not belong to the class's scope. |
Friendship is One-Way | If a function is declared as a friend of a class, it does not automatically make the class a friend of the function. |
Used for Special Cases | Typically used when two or more classes need to work closely together or for operator overloading. |
Friend Function Declaration
A friend function is declared inside the class using the friend
keyword, but it is defined outside of the class.
Syntax:
class ClassName {
private:
// Private members
int privateData;
public:
// Friend function declaration
friend void friendFunction(ClassName& obj);
};