Friend Class Final Notes
Friend Class Final Notes
Introduction:
In C++, a class is a user-defined type or data structure that
includes data and functions as members and whose access is controlled by
the three access specifiers private, protected, and public. Generally, the
private data members of a class can accessible within that class only and
protected members can only be accessed by derived classes.
According to the data hiding concept, Access to members of a C++ class is
usually restricted. (we cannot access the (restricts the access of) private and
protected members from outside the class (global functions cannot access
the private members of a class)). That means a class cannot access the
private members of another class. Similarly, a class that doesn’t inherit
another class cannot access its protected members. Here, we are not talking
about public members because they are accessible outside the class upon an
object, but still, if we are trying to access it will prompt an error.
For example:
class MyClass
{
private:
int member1;
};
int main()
{
MyClass obj;
obj.member1 = 5; // Error! Cannot access private members from
here.
}
In some situation, we need to access the private or protected members
from outside of the class (In C++, global functions cannot access the private
members of a class. However, sometimes we need a global function to
access private members to perform certain operations, without defining it
inside the class).
This is where friend functions come into play.
Friend function:
A friend function is a non-member function that have a
privilege (permissions) to access all private and protected members
(variables and functions) to perform operations, even though it is not a
member function of that class. A Friend Function can be either a member
function of another class or a global function (defined outside the scope of
the class).
Friend class:
Friend classes are those classes that have permission to
access private and protected members of the class in which they are
declared. The main thing to note here is that if the class is made friends of
another class, then it can access all the private members of that class.