Explain in detail what are friendly functions and classes in C++. Give examples in code
- User
Explain in detail what are friendly functions and classes in C++. Give examples in code
- Assistant
In C++, a friendly function or class is a concept of allowing extra access to the private and protected members of a class to another function or class. It is a way to provide specific flexibility and control while maintaining encapsulation.
Friendly Functions: A friendly function is a non-member function that is declared inside a class. It allows access to the private and protected members of the class. To declare a friend function, the keyword
friendis used in the class declaration. The friend function can then access all the members of the class, including private and protected members.Here is an example of a friendly function:
class MyClass { private: int privateData; public: MyClass(int data) : privateData(data) {} friend void printPrivateData(MyClass obj); }; void printPrivateData(MyClass obj) { std::cout << obj.privateData << std::endl; } int main() { MyClass obj(10); printPrivateData(obj); // Output: 10 return 0; }In this example, the function
printPrivateDatais a friendly function of the classMyClass. It can access the private memberprivateDataof the class, and print its value.Friendly Classes: A friendly class is a class that has access to the private and protected members of another class. It can be achieved by declaring the class as a
friendinside another class. This allows the friendly class to access all the members, including private and protected members, of the class that declared it as its friend.Here is an example of a friendly class:
class MyClass { private: int privateData; public: MyClass(int data) : privateData(data) {} friend class FriendClass; }; class FriendClass { public: void printPrivateData(MyClass obj) { std::cout << obj.privateData << std::endl; } }; int main() { MyClass obj(10); FriendClass fc; fc.printPrivateData(obj); // Output: 10 return 0; }In this example, the class
FriendClassis a friendly class of the classMyClass. It can access the private memberprivateDataof theMyClassobject and print its value.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.