1.76k likes | 3.94k Views
Friend Function. Friend Function. Any data which is declared private inside a class is not accessible from outside the class . A non-member function cannot have an access to the private data of a class.
E N D
Friend Function Any data which is declared private inside a class is not accessible from outside the class. A non-member function cannot have an access to the private data of a class. C++ support a special function to access private data of class called friend function or friendly fun.
Friend Function A friend function is used to access private data in a class from outside the class. A friend function is not a member of a class but has access to the class's private members. To make a fun friend, the fun declaration should be preceded by the keyword friend
Friend Function Class s4 { …. …. public: friend void show();// declaration }; Void show() // definition { ….. }
Friend Function Friend fun def does not need the keyword and scope resolution opr (::) Friend fun are not in the scope of any class, so they cannot invoked using class object. They invoked like an ordinary functionin c language A friend can be declared in any number of classes.
Friend Function • class myclass { • int a, b; • public: • friend int sum(myclass x); • void set_ab(inti, int j); • }; • void myclass::set_ab(inti, int j) • { a = I; b = j; } • intsum(myclass x) • { return x.a + x.b; } • int main() • { • myclass n; • n.set_ab(3, 4); • cout<< sum(n); • }
Friend Function Characteristics • The keyword friend is placed only in the function declaration of the friend function and not in the function definition. • It is possible to declare a function as friend in any number of classes. • When a class is declared as a friend, the friend class has access to the private data of the classthat made this a friend. • A friend function, even though it is not a member function, would have the rights to access the private members of the class. • It is possible to declare the friend function as either private or public. • The function cannot be invoked with class object. • The friend function has its argument as objects.