WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Intermediate · question 38 of 100

What is a friend function in C++? When should you use it?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

In C++, a friend function is a function that is declared inside a class and has access to its private and protected members, even though it is not a member function of the class. A friend function can be either a standalone function or a member function of another class.

The syntax for declaring a friend function is as follows:

    class MyClass {
        friend ReturnType functionName(parameters);
        // ...
    };

The friend function declaration must appear inside the class definition, but the definition of the friend function can appear outside the class definition. When the friend function is called, it can access the private and protected members of the class as if they were its own members.

For example:

    class MyClass {
        private:
        int x;
        
        public:
        MyClass(int x) : x(x) {}
        
        friend void printX(MyClass obj);
    };
    
    void printX(MyClass obj) {
        std::cout << "x = " << obj.x << std::endl;
    }
    
    int main() {
        MyClass obj(10);
        
        printX(obj);
        
        return 0;
    }

In this example, the printX() function is declared as a friend of the MyClass class. When the printX() function is called, it can access the private member x of the MyClass object passed as a parameter.

Friend functions are useful when you need to provide external functions with access to the private members of a class, without making those members public. However, they should be used sparingly, as they can potentially violate the encapsulation of the class and make the code less maintainable.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics