1 / 7

Friend Function

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.

tariq
Download Presentation

Friend Function

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Friend Function

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

  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. Friend Function Class s4 { …. …. public: friend void show();// declaration }; Void show() // definition { ….. }

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

  6. 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); • }

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

More Related