Define following terms: a) Friend class and friend function. b) Friend Pointer c) Data hiding d) Data Encapsulation


Q.) Define following terms:

a) Friend class and friend function. b) Friend Pointer c) Data hiding d) Data Encapsulation

Subject: object oriented programming

a) Friend class and friend function:

Friend class:

  • A friend class is a class that is granted access to the private and protected members of another class, even though it is not a member of that class.
  • This access is granted through a friend declaration, which is typically placed in the header file of the class that wants to grant access to its members.
  • The syntax for a friend declaration is as follows:
class A {
  friend class B;
};
  • This declaration allows the class B to access the private and protected members of the class A.

Friend function:

  • A friend function is a function that is granted access to the private and protected members of a class, even though it is not a member of that class.
  • This access is granted through a friend declaration, which is typically placed in the header file of the class that wants to grant access to its members.
  • The syntax for a friend declaration is as follows:
class A {
  friend void f();
};

void f() {
  // Access private and protected members of A
}
  • This declaration allows the function f to access the private and protected members of the class A.

b) Friend Pointer:

  • Friend pointer is a pointer that holds the reference of the private/protected members of another class.
  • Friend Pointer works on the concept of the friend function i.e. If a class B holds the reference to the private/protected pointer of Class A then the class B is declared as friend of class A.
  • Friend pointer is implicitly declared by the compiler when a class is declared as a friend.
  • Friend pointers are used to share private/protected data between classes.

c) Data hiding:

  • Data hiding is a mechanism to restrict the direct access of a class's internal data by other classes.
  • It helps in achieving encapsulation and data security.
  • In data hiding, we define the data members of a class as private and expose public methods to access and modify them.

d) Data Encapsulation:

  • Data encapsulation is a mechanism that bundles the data and methods that operate on that data together as a single unit, called an object.
  • It helps in achieving data hiding and abstraction.
  • In data encapsulation, we define the data members and methods of a class together and restrict the access of data members by other classes.