April 24, 2023

Friend Function

Posted on April 24, 2023  •  3 minutes  • 440 words

In C++, classes have three access modifiers that determine the level of access to class members. These are: public, private, and protected.

Private and protected members are accessible only within the class and its subclasses, whereas public members are accessible anywhere.

Private members are declared with the private keyword in the class definition. Private members cannot be accessed outside of the class or its friend functions. This means that only the members of the class or its friend functions can access them. Private members are often used to hide implementation details of a class from its users.

Example:

class A {
public:
    void setX(int a) // public member function
    { 
        x = a; 
    }
private:
    int x;  // private member
};

int main() {
  A obj;
  obj.setX(10);  // correct, setX is public
  //obj.x = 10;  // error, x is private
  return 0;
}

In this example, x is a private member of A, and setX is a public member function that can be used to modify the value of x. However, attempting to access x directly from main() results in a compiler error.

How to access private members from outside the class?

Here is the answer Friend Function

Friend Function:

A friend function is a function that is declared inside a class but is not a member of that class. However, the friend function is granted access to the private and protected members of the class, which means it can access and modify those members directly.

To declare a friend function in C++, you need to include the friend keyword in the class definition, followed by the function prototype.

Syntax:

friend return_type functionName(arguments);

Example:

#include<iostream>

class A 
{
public:
    A(int a){ x = a; }
    friend void myFriendFunction(A obj);
private:
    int x;
};

void myFriendFunction(A obj) {
  // access to private member x here
  std::cout << obj.x << std::endl;
}

int main() {
  A obj(10);
  myFriendFunction(obj);
  return 0;
}

In this example, the function myFriendFunction is declared as a friend of the class A. The function takes an object of the A as a parameter and is able to modify the private member x of that object.

Important Note:

friend functions do not belong to the class they are declared in, and they cannot access the this pointer of the class. They are regular functions that have access to the private and protected members of the class they are declared as a friend of.

Friend functions can be useful in situations where you want to provide access to a class’s private members to a function that is not a member of the class, without having to make the members public.

Follow me

I work on everything coding and share developer memes