C++ is a middle-level language. It consists of both low-level and high-level language features. It was introduced as an enhancement to the C language and was initially named ‘C with classes’. In 1983, it was renamed C++. It supports all object-oriented programming features, such as data hiding, polymorphism, encapsulation, and inheritance.

All C++ compiler manufacturers support ANSI standards. Thus, it makes C++ one of the most highly portable programming languages. It is a free form programming language that is statically typed, case sensitive, and general-purpose. The three essential parts of C++ are the core language, standard library, and a standard template library (STL).

You can use C++ in any application domain. It is a trusted partner of most software developers. They used it for the direct manipulation of the hardware under real-time constraints. C++ is the other first choice for budding software developers who want to learn basic concepts.

What is the Friend Function in C++?

The friend function in C++ is defined outside the scope of the class. It has the authority to access all protected members and private members of the class. Friends are not member functions, but the prototypes for friend functions appear in the class function only. It covers class template, class, function template, function, and member functions, in which the entire members of the class are friends.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Syntax of Friend Function in C++

You can declare the friend function using the keyword “friend” inside the body of the class.

class Box {

   double width;

    public:

        double length;

        friend void printWidth ( Box box ) ;

        void setWidth ( double wid ) ;

} ;

Features of Friend Function in C++

  • The friend function is invoked like a regular function without using the object and is declared in the public or private part.
  • It is not in the scope of the class that declares it as a friend.
  • It has to use the object name and dot membership operator with the member name to access the member names.

Advantages of Friend Function in C++

  • The friend function allows the programmer to generate more efficient codes.
  • It allows the sharing of private class information by a non-member function.
  • It accesses the non-public members of a class easily.
  • It is widely used in cases when two or more classes contain the interrelated members relative to other parts of the program.
  •  It allows additional functionality that is not used by the class commonly.

How to declare a Friend Function in C++?

All the friend class members become friend functions when a class is declared as a friend class. You can display the friend function in C++ in the following ways:

Class class_name

{

  Friend data_type function_name(argument/s);

};

Another method of declaration can be:

class classB;

 class classA {

     // ClassB is a friend class of ClassA

      friend class ClassB;

……

}

class classB {

……

}

The members of class A can be accessed from class B. The members of Class B can’t be accessed from inside Class A.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example of Friend Function in C++

Example 1:

Simple program showing the working of the 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:

FriendFunctionsInC_Plus_Plus_1

Example 2:

Adding members of two different classes using the friend function:

#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:

FriendFunctionsInC_Plus_Plus_2

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 3:

Printing the length of a box using the friend function:

#include <iostream>

using namespace std;

class Box

{

  private:

    int length;

  public:

    box(): length ( 0 ) { }

    friend int printLength(Box); // friend function

};

int printLength (Box b)

{

  b.length += 10;

   return b.length;

}

int main()

{

  Box b;

  Cout << “Length of box:” <<printLength(b)<<endl;

  Return 0 ;

}

Output:

FriendFunctionsInC_Plus_Plus_3

C++ Friend Class

Now, assume that class B is the friend class of class A. Thus, class B has access to all the members of class A. The function add() is created in class B. This function returns the sum of numA and numB. It is easy to create objects of class A inside class B, as the latter is a friend class. The following is the program that showcases the working of the C++ 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:

FriendFunctionsInC_Plus_Plus_4.

Wrapping Up:

Friend function in C++ is the creative function that breaks the data hiding in an object-oriented programming language. The data hiding prevents the access of private members externally from the class. The protected members are inaccessible from the outside and can only be accessed by the derived classes.

Learn all about the features, declaration, and applications of the friend function from Simplilearn or you can also sign up on ‘SkillUp’ which is a learning platform from Simplilearn, wherein students can take free online courses for C++. It is vital to get all technical and conceptual understanding of friend functions to brush your software development skills. Explore different functions in C++.

What you need to excel today is mastery over the key software skills and tools that top companies are using. This extends beyond 1 programming language. Simplilearn’s Post Graduate Program in Full Stack Web Development program is a unique bootcamp designed to cater to this need. Learn over 30 top software development and programming skills and tools and perfect them with applied projects and interactive labs for hands-on practice. The certificate from Caltech CTME that you’d receive at the end of the program will prove to be your biggest endorsement in your attempt to build a successful software development career anywhere in the world. Get started today.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 15 Apr, 2024

6 Months$ 8,000
Full Stack Java Developer

Cohort Starts: 2 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 3 Apr, 2024

11 Months$ 1,499
Full Stack Developer - MERN Stack

Cohort Starts: 3 Apr, 2024

6 Months$ 1,449