Presentation is loading. Please wait.

Presentation is loading. Please wait.

Friend Function. 2 Any data which is declared private inside a class is not accessible from outside the class. A non-member function cannot have an access.

Similar presentations


Presentation on theme: "Friend Function. 2 Any data which is declared private inside a class is not accessible from outside the class. A non-member function cannot have an access."— Presentation transcript:

1 Friend Function

2 2 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.

3 3 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

4 4 Friend Function Class s4 { …. public: friend void show();// declaration }; Void show() // definition { ….. }

5 5 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 function in c language A friend can be declared in any number of classes.

6 6 Friend Function class myclass { int a, b; public: friend int sum(myclass x); void set_ab(int i, int j); }; void myclass::set_ab(int i, int j) { a = I; b = j; } int sum(myclass x) { return x.a + x.b; } int main() { myclass n; n.set_ab(3, 4); cout << sum(n); }

7 7 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 class that 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.


Download ppt "Friend Function. 2 Any data which is declared private inside a class is not accessible from outside the class. A non-member function cannot have an access."

Similar presentations


Ads by Google