The Wayback Machine - https://web.archive.org/web/20241126215335/https://www.geeksforgeeks.org/friend-class-function-cpp/
Open In App

Friend Class and Function in C++

Last Updated : 14 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node.

We can declare a friend class in C++ by using the friend keyword.

Syntax:

friend class class_name;    // declared in the base class

Friend class


Example:

C++
// C++ Program to demonstrate the
// functioning of a friend class
#include <iostream>
using namespace std;

class GFG {
private:
    int private_variable;

protected:
    int protected_variable;

public:
    GFG()
    {
        private_variable = 10;
        protected_variable = 99;
    }

    // friend class declaration
    friend class F;
};

// Here, class F is declared as a
// friend inside class GFG. Therefore,
// F is a friend of class GFG. Class F
// can access the private members of
// class GFG.
class F {
public:
    void display(GFG& t)
    {
        cout << "The value of Private Variable = "
             << t.private_variable << endl;
        cout << "The value of Protected Variable = "
             << t.protected_variable;
    }
};

// Driver code
int main()
{
    GFG g;
    F fri;
    fri.display(g);
    return 0;
}

Output
The value of Private Variable = 10
The value of Protected Variable = 99

Note: We can declare friend class or function anywhere in the base class body whether its private, protected or public block. It works all the same.

Friend Function

Like a friend class, a friend function can be granted special access to private and protected members of a class in C++. They are not the member functions of the class but can access and manipulate the private and protected members of that class for they are declared as friends.

A friend function can be:

  1. A global function
  2. A member function of another class
Friend Function in C++ with Example

Friend Function in C++

Syntax:

friend return_type function_name (arguments);    // for a global function
or
friend return_type class_name::function_name (arguments); // for a member function of another class

For more on friend functions and access control, check out our Complete C++ Course, where you’ll learn advanced class design techniques.

friend function syntax

Friend Function Syntax

1. Global Function as Friend Function

We can declare any global function as a friend function. The following example demonstrates how to declare a global function as a friend function in C++:

Example:

C++
// C++ program to create a global function as a friend
// function of some class
#include <iostream>
using namespace std;

class base {
private:
    int private_variable;

protected:
    int protected_variable;

public:
    base()
    {
        private_variable = 10;
        protected_variable = 99;
    }
    
      // friend function declaration
    friend void friendFunction(base& obj);
};


// friend function definition
void friendFunction(base& obj)
{
    cout << "Private Variable: " << obj.private_variable
         << endl;
    cout << "Protected Variable: " << obj.protected_variable;
}

// driver code
int main()
{
    base object1;
    friendFunction(object1);

    return 0;
}

Output
Private Variable: 10
Protected Variable: 99

In the above example, we have used a global function as a friend function. In the next example, we will use a member function of another class as a friend function.

2. Member Function of Another Class as Friend Function

We can also declare a member function of another class as a friend function in C++. The following example demonstrates how to use a member function of another class as a friend function in C++:

Example:

C++
// C++ program to create a member function of another class
// as a friend function
#include <iostream>
using namespace std;

class base; // forward definition needed
// another class in which function is declared
class anotherClass {
public:
    void memberFunction(base& obj);
};

// base class for which friend is declared
class base {
private:
    int private_variable;

protected:
    int protected_variable;

public:
    base()
    {
        private_variable = 10;
        protected_variable = 99;
    }

    // friend function declaration
    friend void anotherClass::memberFunction(base&);
};

// friend function definition
void anotherClass::memberFunction(base& obj)
{
    cout << "Private Variable: " << obj.private_variable
         << endl;
    cout << "Protected Variable: " << obj.protected_variable;
}

// driver code
int main()
{
    base object1;
    anotherClass object2;
    object2.memberFunction(object1);

    return 0;
}

Output
Private Variable: 10
Protected Variable: 99

Note: The order in which we define the friend function of another class is important and should be taken care of. We always have to define both the classes before the function definition. Thats why we have used out of class member function definition.

Features of Friend Functions

  •  A friend function is a special function in C++ that in spite of not being a member function of a class has the privilege to access the private and protected data of a class.
  • A friend function is a non-member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function.
  • The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition or call.
  • A friend function is called like an ordinary function. It cannot be called using the object name and dot operator. However, it may accept the object as an argument whose value it wants to access.
  • A friend function can be declared in any section of the class i.e. public or private or protected.

Below are some more examples of friend functions in different scenarios:

A Function Friendly to Multiple Classes

C++
// C++ Program to demonstrate 
// how friend functions work as
// a bridge between the classes
#include <iostream>
using namespace std;

// Forward declaration
class ABC; 

class XYZ {
    int x;

public:
    void set_data(int a) 
    { 
      x = a; 
    }

    friend void max(XYZ, ABC);
};

class ABC {
    int y;

public:
    void set_data(int a) 
    { 
      y = a; 
    }

    friend void max(XYZ, ABC);
};

void max(XYZ t1, ABC t2)
{
    if (t1.x > t2.y)
        cout << t1.x;
    else
        cout << t2.y;
}

// Driver code
int main()
{
    ABC _abc;
    XYZ _xyz;
    _xyz.set_data(20);
    _abc.set_data(35);

    // calling friend function
    max(_xyz, _abc); 
    return 0;
}

Output
35

The friend function provides us with a way to access private data but it also has its demerits. Following is the list of advantages and disadvantages of friend functions in C++:

Advantages of Friend Functions

  • A friend function is able to access members without the need of inheriting the class.
  • The friend function acts as a bridge between two classes by accessing their private data.
  • It can be used to increase the versatility of overloaded operators.
  • It can be declared either in the public or private or protected part of the class.

Disadvantages of Friend Functions

  • Friend functions have access to private members of a class from outside the class which violates the law of data hiding.
  • Friend functions cannot do any run-time polymorphism in their members.

Important Points About Friend Functions and Classes

  1. Friends should be used only for limited purposes. Too many functions or external classes are declared as friends of a class with protected or private data access lessens the value of encapsulation of separate classes in object-oriented programming.
  2. Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.
  3. Friendship is not inherited. (See this for more details)
  4. The concept of friends is not in Java.


Previous Article
Next Article

Similar Reads

Difference Between Friend Function and Virtual Function in C++
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and
3 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Difference between Static and Friend Function in C++
Static Function: It is basically a member function that can be called even when the object of the class is not initialized. These functions are associated with any object and are used to maintain a single copy of the class member function across different objects of the class. This function is denoted by using the static keyword. Friend Function: I
3 min read
Using Non-Member Friend Functions With Vector in C++ STL
In C++, Non-member buddy functions may access a class's private members while not being members. The class definition declares them friend. Vector containers, dynamic arrays in C++ Standard Library (STL), may dynamically resize as members are added or deleted. You may need to establish a new class with a vector to utilize non-member friend methods
2 min read
Difference between Base class and Derived class in C++
Base Class: A base class is a class in Object-Oriented Programming language, from which other classes are derived. The class which inherits the base class has all members of a base class as well as can also have some additional properties. The Base class members and member functions are inherited to Object of the derived class. A base class is also
2 min read
C++ Interview Questions on Virtual Function and Abstract Class
Diving into the depths of C++ programming requires a solid grasp of some of its most important topics, such as virtual functions and abstract classes. These concepts are not only fundamental to mastering the language but are also frequent subjects in technical interviews. In this interview preparation guide, you will explore a comprehensive list of
5 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
How to Provide a Swap Function for My Class in C++?
In C++, providing a swap function for the class allows efficient swapping of the objects of that class type which can be important for many algorithms like sorting algorithms or container manipulations. In this article, we will learn how to implement a swap function for our own user defined class. swap Function for User Defined Class in C++There ar
3 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &lt;iostream&gt; using namespace std; class Base { public: void print() { cout &lt;&lt; &quot;Base class print function \n&quot;; } void invoke() { cout &lt;&lt; &quot;Base class invoke function \n&quot;;
2 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Difference between namespace and class
Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to diffe
2 min read
Operator Overloading '<<' and '>>' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include <iostream> using namespace std; class Gfg { public: void printHello() { cout << "hello gfg-class specific" << endl; } }; void printHello() { cout << "hello gf
5 min read
Difference Between Object And Class
Class is a detailed description, the definition, and the template of what an object will be. But it is not the object itself. Also, what we call, a class is the building block that leads to Object-Oriented Programming. It is a user-defined data type, that holds its own data members and member functions, which can be accessed and used by creating an
6 min read
C++ string class and its applications
In C++ we can store string by one of the two ways – C style stringsstring class (discussed in this post) In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings. C++ string class internally uses char array to store character but all memory management, allocation,
6 min read
C++ String Class and its Applications
C++ string class and its applications have more functions as discussed in this article String vs Character Array In C++, in addition to a character array, there exists a similar kind of way to implement string, that is using a string class which is a part of C++ standard library.We need to add a header file to implement string using string class. T
4 min read
Difference between Shallow and Deep copy of a class
Shallow Copy: Shallow repetition is quicker. However, it's "lazy" it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each of the first and therefore the copy can have pointers that reference constant underlying knowledge. Deep C
5 min read
Difference Between Structure and Class in C++
In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whoever uses it in code, while a class by default hides all its implementation details and will therefore by default prevent the p
3 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
unordered_multimap begin() and end() function in C++ STL
The unordered_multimap::begin() is a built-in function in C++ STL that returns an iterator pointing to the first element in the container or to the first element in one of its buckets. Syntax: unordered_multimap_name.begin(n) Parameters: The function accepts one parameter. If a parameter is passed, it returns an iterator pointing to the first eleme
5 min read
list cbegin() and cend() function in C++ STL
The list::cbegin() is a built-in function in C++ STL which returns a constant random access iterator which points to the beginning of the list. Hence the iterator obtained can be used to iterate container but cannot be used to modify the content of the object to which it is pointing even if the object itself is not constant.Syntax: list_name.cbegin
2 min read
map cbegin() and cend() function in C++ STL
map::cbegin() is a built-in function in C++ STL that returns a constant iterator referring to the first element in the map container. Since map container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container's sorting criterion. Syntax: map_name.cbegin()Parameters: The function d
3 min read
map crbegin() and crend() function in C++ STL
map::crbegin() is a built-in function in C++ STL that returns a constant reverse iterator referring to the last element in the map container. Since map container contains the element in an ordered way, crbegin() will point to that element that will come last according to the container's sorting criterion. Syntax: map_name.crbegin()Parameters: The f
3 min read
set crbegin() and crend() function in C++ STL
The set::crbegin() is a built-in function in C++ STL which returns a constant iterator pointing to the last element in the container. The iterator cannot be used to modify the elements in the set container. The iterators can be increased or decreased to traverse the set accordingly. Syntax: constant_iterator set_name.crbegin() Parameters: The funct
2 min read
set cbegin() and cend() function in C++ STL
The set::cbegin() is a built-in function in C++ STL which returns a constant iterator pointing to the first element in the container. The iterator cannot be used to modify the elements in the set container. The iterators can be increased or decreased to traverse the set accordingly. Syntax: constant_iterator set_name.cbegin() Parameters: The functi
2 min read
list rbegin() and rend() function in C++ STL
list::rbegin() is an inbuilt function in C++ STL that returns a reverse iterator which points to the last element of the list. Syntax: list_name.rbegin()Parameter: This function does not accept any parameters. Return value: It returns a reverse iterator which points to the last element of the list. Below program illustrates the above function: C/C+
2 min read
list crbegin() and crend() function in C++ STL
The list::crbegin() is a built-in function in c++ STL that returns a constant reverse iterator which points to the last element of the list i.e reversed beginning of container. The elements cannot be modified or changed as the iterator is a constant one. Syntax: list_name.crbegin()Parameters: The function does not accept any parameters. Return valu
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg