What is a friend function? What are the merits and demerit of using friend function. Explain with example.
Question
What is a friend function? What are the merits and demerits of using friend function? Explain with example.
Solution
A friend function in C++ is a function that has the right to access all private and protected members (variables and functions) of the class, even though it is not a member of that class. It is defined using the keyword 'friend' before the function name.
Here is an example of a friend function:
class MyClass {
private:
int myVar;
public:
MyClass() : myVar(0) {}
friend void changeMyVar(MyClass& obj, int value);
};
void changeMyVar(MyClass& obj, int value) {
obj.myVar = value; // Directly accessing private member
}
In this example, changeMyVar
is a friend function of the class MyClass
. It can directly access and modify the private member myVar
of MyClass
.
Merits of using friend function:
- It can access the private and protected members of the class, which provides more flexibility.
- It can be used when a certain functionality cannot be achieved by the member functions of the class.
- It can be used to overload certain operators for the class.
Demerits of using friend function:
- It violates the encapsulation principle of Object Oriented Programming, as it accesses the private and protected members of the class directly.
- The use of friend functions increases the risk of data being accidentally modified, as it has access to the private members of the class.
- If not used carefully, it can make the code more complex and harder to debug.
Similar Questions
A function can be described or defined in many ways. List thesedifferent ways, and explain how each can be used to determinewhether a relation is a function.
Which of the following is a composite measure that includes social contact with peers, popularity with peers, friendship, and social skills?
In the case of friend operator overloaded functions how many maximum object arguments a unary operator overloaded function can take?a.1b.0c.3d.2
What is it about the internet that makes it possible to share things that one might not ordinarily share in person, perhaps even with close friends?
Based on networking theory, _____ tie people together based on a common element such as an area of interest or friendship.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.