Skip to main content

Friend Class in C++

 

Friend Class in C++

Definition

A friend class in C++ is a class that has access to the private and protected members of another class. Normally, private and protected members of a class are only accessible to the class's own methods or friends. To make a class a friend of another class, we use the keyword friend inside the class definition.

 

Why Do We Use Friend Classes?

We use a friend class to allow another class access to private or protected members of a class without making it a subclass or adding numerous getter and setter functions.

 

Need for Friend Classes

1.      Access Private Data: A friend class can work directly with private or protected members of another class.

2.      Convenience: Eliminates the need for additional public methods to expose private data.

3.      Specialized Use: Useful in scenarios where two or more classes need close collaboration and data sharing.

 

Advantages of Friend Classes

1.      Direct Access: The friend class has direct access to private and protected members of the other class.

2.      Simplifies Design: Reduces the need for additional public functions to share data between classes.

3.      Improves Collaboration: Facilitates close interaction between two tightly coupled classes.

  

Disadvantages of Friend Classes

1.      Breaks Encapsulation: It violates the principle of data hiding by allowing private data to be accessed directly.

2.      Tight Coupling: Increases dependency between classes, making the design harder to maintain.

3.      Not Inherited: Friendship is not inherited, so derived classes do not automatically gain access.

 

Example of a Friend Class

#include <iostream>

using namespace std;

 

class abc {

private:

    int sal = 40000;

protected:

    int pm = 5000;

public:

    friend class AjaySir;

};

 

class AjaySir {

public:

    void show(abc &obj) {

        cout << "Salary is " << obj.sal << endl;

                   cout<<"Pocket Money is " << obj.pm << endl;

    }

};

 

int main() {

    abc o1;

    AjaySir f1;

    f1.show(o1);

    return 0;

}

 

 

How Friend Classes Work?

  • Declared as a friend inside the class definition.
  • The friend class gains access to all private and protected members of the class.
  • Methods of the friend class use the object of the original class to interact with private data.

 

Key in mind at the time of interview:

  • Friendship is not mutual: If Class A declares Class B as a friend, Class B does not automatically make Class A its friend.
  • Friendship is not transitive: If Class A is a friend of Class B and Class B is a friend of Class C, it doesn’t mean Class A is a friend of Class C.
  • Friendship is not inherited: A derived class of a friend class does not automatically gain friendship.

 

Real-Life Example

A house with locked rooms (private data) is accessible only to the owner (class methods). However, the owner can give a trusted family (friend class) complete access to the house. Members of the family can then access the private areas directly.

For instance, AjaSir (friend class) has access to your private and protected data to manage tasks efficiently.

 

When to Avoid Friend Classes?

1.      When getters and setters can achieve the same functionality.

2.      When excessive use of friend classes complicates the design and violates the principle of encapsulation

 

 

#Happy Coding keep learning

Comments

Popular posts from this blog

C++ Lec-2 Introduction to Object-Oriented Programming (OOP) in C++

  Introduction to Object-Oriented Programming (OOP) in C++ Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to organize software design. It allows for modelling real-world entities and relationships in a program. C++ is an object-oriented programming language that provides features to implement OOP concepts effectively. Key Concepts of OOP   Class and Object o    Class : A blueprint for creating objects. It defines properties and behaviours of objects.   class Car { public:     string brand;     string model;     int year; };   o    Object : An instance of a class.   Car car1; car1.brand = "Mahindra"; car1.model = "THAR"; car1.year = 2024;   Encapsulation o    Encapsulation is the bundling of data and methods that operate on that data within a single unit, or class. It restricts direct acces...

C++ Lec-1 (Introduction to Programming Languages)

  Introduction to Programming Languages ________________________________________________________________________ P rogramming languages are formal languages comprising a set of instructions that produce various kinds of output. They are used in computer programming to implement algorithms and control the behavior of machines. Language Generation Programming languages have evolved through several generations: First Generation (1GL) : Machine language, the most basic level of programming languages, consisting of binary code. Second Generation (2GL) : Assembly language, a low-level language with a strong correspondence to the machine language instructions. Third Generation (3GL) : High-level languages like C, C++, Java, Python, which are more abstract and easier for humans to understand. Fourth Generation (4GL) : Languages closer to human language, often used for database querying and report generation (e.g., ...

DATA TYPE in C/C++

  BUILT IN OF PRIMARY DATA TYPE     int (Integer) float(Floating-point) double (Double Floating-point) char (Character) wchar_t (Wide Character) bool (Boolean) void (Empty) Modified Data Types List    signed int - (used for integers) unsigned - int (can only store positive integers) short (used - for small integers (range -32768 to 32767)) unsigned short - (used for small positive integers (range 0 to 65,535)) Long - (used for large integers) unsigned long - (used for large positive integers ) long long - (used for very large integers) unsigned long long - (used for very large positive integers) long double - (used for large floating-point numbers) signed char - (used for characters (guaranteed range -127 to 127)) unsigned char - (used for characters (range 0 to 255)) Derived Type Data Type    Function Array Pointers References User-Defined Data Type   Class Structure Union Enumeration Typedef defined DataType