Definition Of Friend Class In C
In this example class rectangle is a friend of class square allowing rectangle s member functions to access private and protected members of square more concretely rectangle accesses the member variable square side which describes the side of the square.
Definition of friend class in c. Example of c friend class. A friend function of the class is defined outside that class scope but it has a right to access all the private and protected members of a class. At the beginning of the program there is an empty declaration of class square. When a class is declared a friend class all the member functions of the friend class become friend functions.
A friend can be a function function template or member function or a class or class. How to declare friend function. A class can also be declared to be the friend of some other class. Since classb is a friend class we can access all members of classa from inside classb.
A class definition starts with the keyword class followed by the class name. However we cannot access members of classb from inside classa. 1 friends should be used only for limited purpose. When we create a friend class then all the member functions of the friend class also become the friend of the other class.
See the following syntax. For example we defined the box data type using the keyword class as follows. A class definition must be followed either by a semicolon or a list of declarations. So the private data can be accessed from this function.
This requires the condition that the friend becoming class must be first declared or defined forward declaration. Though this example gives you what idea about the concept of friend function. The non member function has to grant an access to update or access the class. There is something else new in this example.
Even though the prototypes for friend functions appear in the class definition friends are not member functions. In c friend means to give permission to a class or function. Here friend function func is declared inside distance class. Even though the prototypes for friend functions appear in the class definition friends are not member functions.
In order to access the private and protected members of a class into friend class we must pass on object of a class to the member functions of friend class. And the class body enclosed by a pair of curly braces. Following are some important points about friend functions and classes. Like friend function a class can also be a friend of another class.
Too many functions or external classes are declared as friends of a class with protected or private data it lessens the value of encapsulation of separate classes in object oriented programming.