friend_func.ppt

9

Click here to load reader

Upload: sujithmv

Post on 28-Sep-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

  • Friend Functions and Friend Classes

  • Friend Functions & Friend ClassesPrivate data of a class is accessible only to member functions.We know a private member cannot be accessed from outside the class. A non member function cannot have access to private data of a class But a Friend function can access private data of a class.Non member functions can access private members of a class using friend functions or friend classes.It permits a function or all functions of another class to access a different classs private members.

  • Friend functionFunction declaration is prefixed by keyword friend.The function definition does not use either the keyword friend or the scope resolution operator ::.

  • To declare a friend functionclass ABC{: :: :public :

    friend void xyz(void); //declaration}; Functions declared with keyword friend are called as friend functions.

  • Friend functionIt cannot be called using the object of the classIt can be invoked like a normal functionA friend function although , not a member function has full access to the private members of the classBut it cannot access Class members directly. It uses object and dot operator with each member name to access both private and public members.A function can be friend to multiple classes.

  • Bridging classes with friends

    If there is a situation where a function is to be shared between two classes .i.e function operating on objects of two different classes. Friend functions can be used to bridge two classes

  • Eg#includeClass ABC;Class XYZ{ int x; public : void setvalue(int i) { x=i;} friend void max(XYZ, ABC);};Class ABC{ int a; public : void setvalue(int i) { a=i;} friend void max(XYZ, ABC);};

  • Void max(XYZ m, ABC n){if(m.x >= n.a) cout
  • Friend ClassesThe Friend Keyword allows a function or all functions of a class to manipulate private members of another class.To declare a class as a friend, use keyword friend with class name and declare it in the class whose private date we want to manipulate.