Friend Class & Friend Functions
In C++, the friend
keyword is used to grant non-member functions or classes access to the private and protected members of a class. This mechanism is often used when you need to provide certain functions or classes with special privileges to access internal data or methods of a class. Here's how friend
works and some interview questions related to it:
Friend Functions:
A friend function is a function that is not a member of a class but has access to its private and protected members. To declare a friend function, you use the friend
keyword inside the class declaration. Here's an example:
In this example, FriendFunction
is declared as a friend function inside the MyClass
definition. It can access the private member privateData
of MyClass
objects.
Interview Questions:
What is a friend function in C++?
A friend function is a function that is not a member of a class but has access to its private and protected members.
Why would you use a friend function?
Friend functions are used to grant non-member functions or classes special access to the private and protected members of a class when it's necessary for the design or implementation of a particular feature.
What is the difference between a friend function and a member function?
Member functions are part of a class and have direct access to its private and protected members. Friend functions are not part of the class but have been granted access to these members.
Can a friend function access static members of a class?
Yes, friend functions can access static members (both data members and member functions) of a class.
Can you have multiple friend functions for a single class?
Yes, you can declare and define multiple friend functions for a single class.
Friend Classes:
A friend class is a class that is granted access to the private and protected members of another class. You declare a friend class by using the friend
keyword inside the class definition. Here's an example:
In this example, FriendClass
is declared as a friend class of MyClass
, which allows it to access the private member privateData
of MyClass
objects.
Interview Questions:
What is a friend class in C++?
A friend class is a class that is granted access to the private and protected members of another class.
What's the difference between a friend function and a friend class?
A friend function is a standalone function that has access to the private and protected members of a class, while a friend class is a whole class that is granted such access.
Can you have multiple friend classes for a single class?
Yes, you can declare multiple friend classes for a single class.
When might you use a friend class instead of a friend function?
You might use a friend class when you want an entire class to have access to the private and protected members of another class, perhaps for implementing a closely related feature or to simplify interactions between the two classes.
Last updated
Was this helpful?