In C++, friend functions are functions that are not members of a class but are granted access to the private and protected members of that class. They can be useful in scenarios where you need to allow external functions or classes to manipulate or access the private data of a class. Here's a sample code that demonstrates how to declare and use a friend function in C++:
#include <iostream>
class MyClass {
private:
int privateData;
public:
MyClass(int data) : privateData(data) {}
// Declare the friend function
friend void FriendFunction(MyClass&);
// Member function to access private data
void DisplayPrivateData() {
std::cout << "Private Data: " << privateData << std::endl;
}
};
// Define the friend function
void FriendFunction(MyClass& obj) {
// The friend function can access private members of MyClass
obj.privateData += 10;
}
int main() {
MyClass myObject(42);
myObject.DisplayPrivateData(); // Display the initial private data
// Call the friend function to modify privateData
FriendFunction(myObject);
myObject.DisplayPrivateData(); // Display the modified private data
return 0;
}
In this example:
We have a MyClass class with a private data member privateData.
We declare the FriendFunction as a friend of the MyClass class by including the
friend keyword in the class declaration.
The FriendFunction is defined outside the class and can access the private member
privateData of MyClass.
In the main function, we create an instance of MyClass and demonstrate how the friend function can modify the private data of the class.
Please note that while friend functions can be useful in certain situations, they should be used sparingly, as they can break encapsulation and make the code less maintainable if overused. It's generally recommended to prefer member functions and accessor methods (getters and setters) for interacting with the private data of a class when possible.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C++, friend functions are functions that are not members of a class but are granted access to the private and protected members of that class. They can be useful in scenarios where you need to allow external functions or classes to manipulate or access the private data of a class. Here's a sample code that demonstrates how to declare and use a friend function in C++:
In this example:
Please note that while friend functions can be useful in certain situations, they should be used sparingly, as they can break encapsulation and make the code less maintainable if overused. It's generally recommended to prefer member functions and accessor methods (getters and setters) for interacting with the private data of a class when possible.