In C++, a friend function is a function that is given special access to the private and protected members of a class. This allows the function to access and modify the internal state of the class, even if the function is not a member of the class.
A friend function is declared using the keyword "friend" before the function declaration, and it is defined outside the class. The friend function can be a member of another class, or it can be a non-member function.
For example, consider the following class called Time:
class Time {
private:
int h/ours;
int minutes;
public:
Time(int h = 0, int m = 0);
friend void addMinutes(Time &t, int m);
}
;
In this example, the Time class has two private members, hours and minutes, and a constructor that sets the initial values. It also has a friend function called addMinutes, which takes two parameters: a reference to a Time object and an integer. The function can access the private members of the Time class, and it can modify them directly.
void addMinutes(Time &t, int m) {
t.minutes += m;
t.hours += t.minutes / 60;
t.minutes %= 60;
}
This function can be used to add a certain number of minutes to a Time object, and it can update the hours and minutes accordingly.
int main() {
Time myTime(3, 45);
addMinutes(myTime, 30);
cout << "Time: " << myTime.hours << ":" << myTime.minutes << endl;
return 0;
}
Output:
Time: 4:15
Friend functions are also used to overload the input and output operators, such as << and >>.
class MyString {
private:
char *str;
public:
MyString(const char *s);
~MyString();
friend ostream& operator<<(ostream& os, const MyString& s);
};
In this case, the << operator is defined as a friend function.
ostream& operator<<(ostream& os, const MyString& s) {
os << s.str;
return os;
}
In summary, friend function in C++ allows a function to have special access to the private and protected members of a class, even if the function is not a member of the class. Friend functions are declared using the keyword "friend" before the function declaration and defined outside the class. They can be a member of another class or a non-member function. Friend functions can be used to overload input and output operators, to perform specific tasks that couldn't be achieved by normal member functions and for access control to the class data. It's important to be aware that friend functions can break the encapsulation of a class and can make the code less maintainable if not used carefully.
Comments
Post a Comment