Friend Function and Friend Classes

Friend Function and Friend Classes In C++

With the aid of examples, we will learn how to build friend classes and friend functions in C++ in this article. friend class A class that has been designated as a friend can access the secret and protected members of other classes.

Sometimes it is advantageous to provide certain class access to another class’s secret members.

For instance, a LinkedList class might be permitted access to Node’s secret members.

A class’ friend function can access all of the class’s private and protected members despite being specified outside the bounds of the class.

Friends are not member functions, despite the fact that the prototypes for friend functions can be found in the class specification.

A class or class template, in which case the entire class and all of its members are friends, or a function, function template, or member function, can also be a friend.

An essential idea in object-oriented programming is data hiding. Private members from outside the class are not allowed access.

Friends functions are those that have access to the class’s private members where they are declared.

Here, it’s important to keep in mind that only that function has access to the member function that the other class has designated as a friend.

The fact that private members cannot be accessed from outside the class has been emphasized. In other words, a non-member function is not permitted access to a class’s secret information.

We might, however, want two classes to share a specific function in some circumstances. Think of a situation where two classes—manager and scientist—have been established.

In order to interact with the objects of each of these classes, we want to call the function income().

In these circumstances, C++ permits the common function to be made friends with both classes, granting the function access to their private data.

Such a function is not required to belong to any of the above types.

The keyword friend/ should come before the function declaration. The function can then be declared elsewhere in the program as a typical C++ function. Neither the scope operator:: nor the keyword friend is used in the definition of the function. Friend functions are those that use the keyword friend when they are declared.

Despite not being a member function, a friend function has full access to the class’s private members.

These unique qualities that make up a friend function are as follows:

  • The class to which it has been labeled a friend does not cover it.
  • It cannot be called using an object of that class because it is outside the scope of the class. Without the assistance of any object, it can be used for any other function.
  • It must utilize an object name and the dot membership operator with each member name because, unlike member functions, it cannot access the member names directly (e.g., C.x)
  • Its meaning is unaffected by whether it is declared in a class’s public or private portion.
  • The objects are typically used as arguments.

Similar to this, protected members are inaccessible to outsiders and can only be accessed by derived classes. For instance,

class MyClass {
    private:
        int member1;
}

int main() {
    MyClass obj;

    // Error! Cannot access private members from here.
    obj.member1 = 5;
}

Friend functions, a C++ feature, allow us to circumvent this restriction and access member functions from outside the class.

A friend class exists as well, which we will discover later in this course.

Friend Function in C++(Friend Function and Friend Classes)

The private and protected data of a class can be accessed using the friend function. In the class’s body, we use the friend keyword to declare a friend function.

class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}

Example 1: Working of friend Function(Friend Function and Friend Classes)

// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
    private:
        int meter;
        
        // friend function
        friend int addFive(Distance);

    public:
        Distance() : meter(0) {}
        
};

// friend function definition
int addFive(Distance d) {

    //accessing private members from the friend function
    d.meter += 5;
    return d.meter;
}

int main() {
    Distance D;
    cout << "Distance: " << addFive(D);
    return 0;
}

Output

Distance: 5

The friend function addFive() in this case has access to both private and public data members.

Although this example helps us understand the idea of a friend function, it doesn’t demonstrate any useful application.

Performing operations on objects belonging to two separate classes would be a more useful application. When that happens, the friend feature can be incredibly useful.

Example 2: Add Members of Two Different Classes(Friend Function and Friend Classes)

// Add members of two different classes using friend functions

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
    
    public:
        // constructor to initialize numA to 12
        ClassA() : numA(12) {}
        
    private:
        int numA;
        
         // friend function declaration
         friend int add(ClassA, ClassB);
};

class ClassB {

    public:
        // constructor to initialize numB to 1
        ClassB() : numB(1) {}
    
    private:
        int numB;
 
        // friend function declaration
        friend int add(ClassA, ClassB);
};

// access members of both classes
int add(ClassA objectA, ClassB objectB) {
    return (objectA.numA + objectB.numB);
}

int main() {
    ClassA objectA;
    ClassB objectB;
    cout << "Sum: " << add(objectA, objectB);
    return 0;
}

Output

Sum: 13

ClassA and ClassB have designated add() as a friend function in this program. Therefore, this function has access to both classes’ private data.

One thing to note is that ClassA uses ClassB for the friend function. ClassB has not yet been defined, though.

// inside classA 
friend int add(ClassA, ClassB);

We require a forward declaration of ClassB in our program for this to function.

// forward declaration
class ClassB;

friend Class in C++(Friend Function and Friend Classes)

The friend keyword in C++ allows us to use a friend Class as well. For instance,

class ClassB;

class ClassA {
   // ClassB is a friend class of ClassA
   friend class ClassB;
   ... .. ...
}

class ClassB {
   ... .. ...
}

All of a class’s member functions change to friend functions when it is designated as a friend class.

We can access every member of ClassA from within ClassB since ClassB is a friend class.

We are unable to access ClassB members from within ClassA, though. It’s because, in C++, friendships can only be granted and not demanded.

Example 3: C++ friend Class(Friend Function and Friend Classes)

// C++ program to demonstrate the working of friend class

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
    private:
        int numA;

        // friend class declaration
        friend class ClassB;

    public:
        // constructor to initialize numA to 12
        ClassA() : numA(12) {}
};

class ClassB {
    private:
        int numB;

    public:
        // constructor to initialize numB to 1
        ClassB() : numB(1) {}
    
    // member function to add numA
    // from ClassA and numB from ClassB
    int add() {
        ClassA objectA;
        return objectA.numA + numB;
    }
};

int main() {
    ClassB objectB;
    cout << "Sum: " << objectB.add();
    return 0;
}

Output

Sum: 13

ClassB is ClassA’s companion class in this instance. As a result, ClassB gets access to ClassA’s members.

We have written a function called add() in ClassB that returns the sum of numA and numB.

We can construct objects of ClassA inside of ClassB because ClassB is a friend class.

you may like:

C++ Goto statement with Example | C++ Programming

This Post Has One Comment

Leave a Reply