Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

Explain in detail what are friendly functions and classes in C++. Give examples in code

  1. User

    Explain in detail what are friendly functions and classes in C++. Give examples in code

  2. 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 friend is 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 printPrivateData is a friendly function of the class MyClass. It can access the private member privateData of 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 friend inside 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 FriendClass is a friendly class of the class MyClass. It can access the private member privateData of the MyClass object and print its value.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Explain in detail what are friendly functions and classes… · The Chat Archive