13.2 C
New York
Tuesday, November 26, 2024

Good friend Perform in C++ and lessons with Examples | 2023


Introduction

On the earth of object-oriented programming, encapsulation stands as a beacon of safe and structured code creation. C++ additional elevates this precept by introducing a robust but even handed characteristic: the good friend perform, which adeptly navigates the wonderful line between sustaining encapsulation and permitting managed entry to class members. This exceptional software, which may entry the personal and guarded members of a category, gives programmers a better diploma of flexibility and effectivity in code growth. Within the midst of preserving the sanctity of information encapsulation, it facilitates a seamless interplay between lessons, fostering a symbiotic relationship that may improve the general performance of a software program system.

On this tutorial, we’ll learn to create a good friend perform in C++ with the assistance of some examples.

Information hiding is a elementary idea in object-oriented programming, and it restricts the entry of personal members from exterior the category.

What’s a Good friend Perform in C++?

A good friend perform in C++ is outlined as a perform that may entry personal, protected, and public members of a category.

The good friend perform is asserted utilizing the good friend key phrase contained in the physique of the category.

Good friend Perform Syntax:

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

Through the use of the key phrase, the ‘good friend’ compiler understands that the given perform is a good friend perform.

We declare a good friend perform contained in the physique of a category, whose personal and protecting information must be accessed, beginning with the key phrase good friend to entry the info. We use them when we have to function between two completely different lessons on the identical time.

What’s Good friend Perform?

Good friend capabilities of the category are granted permission to entry personal and guarded members of the class in C++. They’re outlined globally exterior the category scope. Good friend capabilities should not member capabilities of the category. So, what precisely is the good friend perform?

A good friend perform in C++ is a perform that’s declared exterior a category however is able to accessing the personal and guarded members of the category. There could possibly be conditions in programming whereby we would like two lessons to share their members. These members could also be information members, class capabilities or perform templates. In such instances, we make the specified perform, a good friend to each these lessons which can permit accessing personal and guarded information of members of the category.

Usually, non-member capabilities can’t entry the personal members of a specific class. As soon as declared as a good friend perform, the perform is ready to entry the personal and guarded members of those lessons.

Upskill with different Programming languages

Consumer-defined Perform sorts

Good friend capabilities in C++ have the next sorts

  • Perform with no argument and no return worth
  • Perform with no argument however with return worth
  • Perform with argument however no return worth
  • Perform with argument and return worth

Declaration of a good friend perform in C++

class class_name
{
   good friend data_type function_name(arguments/s); //syntax of good friend perform. 
};

Within the above declaration, the key phrase good friend precedes the perform. We are able to outline the good friend perform anyplace in this system like a traditional C++ perform. A category’s perform definition doesn’t use both the key phrase good friend or scope decision operator (: 🙂.

Good friend perform known as as function_name(class_name) and member perform known as as class_name. function_name.

Use of Good friend perform in C++

As mentioned, we require good friend capabilities at any time when we’ve to entry the personal or protected members of a category. That is solely the case when we don’t need to use the objects of that class to entry these personal or protected members.

To know this higher, allow us to take into account two lessons: Tokyo and Rio. We would require a perform, metro(), to entry each these lessons with none restrictions. With out the good friend perform, we would require the article of those lessons to entry all of the members. Good friend capabilities in c++ assist us keep away from the situation the place the perform must be a member of both of those lessons for entry.

Necessary C++ Subjects to Know

C++ perform overloading

Two capabilities can have the identical identify if the quantity and sort of argument handed is completely different. Capabilities which have the identical identify , however have completely different arguements are known as Overloading capabilities.

Good friend capabilities are additionally utilized in operator overloading. The binary operator overloading in c++ utilizing the good friend perform could be performed as defined beneath.

Binary operator overloading in C++ utilizing Good friend perform

The operator overloading perform precedes a good friend key phrase on this method. It additionally declares a perform class scope. The good friend operator perform takes 2 parameters in a binary operator. It then varies one parameter in a unary operator.

The perform can be applied exterior the category scope. However, the working and the implementation are the identical because the binary operator perform.

If you wish to construct your data in C++, take into account getting licensed. This Introduction to C++ Free Course will enable you to be taught the required abilities and likewise a certificates on completion that may be added to your social profiles. You may as well take a look at our Full Stack Program by IIT Roorkee.

Traits of Good friend Perform in C++

  • The perform just isn’t within the ‘scope’ of the category to which it has been declared a good friend.
  • Good friend performance just isn’t restricted to just one class
  • Good friend capabilities generally is a member of a category or a perform that’s declared exterior the scope of sophistication.
  • It can’t be invoked utilizing the article as it isn’t within the scope of that class.
  • We are able to invoke it like several regular perform of the category.
  • Good friend capabilities have objects as arguments.
  • It can’t entry the member names immediately and has to make use of dot membership operator and use an object identify with the member identify.
  • We are able to declare it both within the ‘public’ or the ‘personal’ half.
  • These are a number of the good friend capabilities in C++ traits

Implementing Good friend Capabilities

Good friend Capabilities could be applied in two methods:

A way of one other class:

We declare a good friend class once we need to entry the personal information members of a specific class.

A International perform:

A ‘international good friend perform’ permits you to entry all of the personal and guarded members of the worldwide class declaration.

A easy instance of a C++ good friend perform used to print the size of the field.

Code:

#embody <iostream>
utilizing namespace std;
class Field
{
   personal:
        int size;
   public:
         Field (): size (0) {}
   good friend int printLength (Field); //good friend perform
};
int printLength (Field b)
{
    b. size +=10;
    return b. size;
}
int principal ()
{
   Field b;
   cout <<” Size of field:” <<printLength (b)<<endl;
    return 0;
}

Output:

           Size of field:10

Easy instance when the perform is pleasant for 2 lessons.

Code:

#embody<iostream>
utilizing namespace std;
class B; //ahead declaration.
class A
{
    int x;
    public:
         void setdata (int i)
           {
              x=i;
           }
    good friend void max (A, B); //good friend perform.
} ;
class B
{
     int y;
     public:
          void setdata (int i)
            {
               y=i;
            }
     good friend void max (A, B);
};
void max (A a, B b)
{
   if (a.x >= b.y)
         std:: cout<< a.x << std::endl;
   else
         std::cout<< b.y << std::endl;
}
  int principal ()
{
   A a;
   B b;
    a. setdata (10);
    b. setdata (20);
    max (a, b);
    return 0;
}

Output:

        20                                         

Within the above instance, max () perform is pleasant to each class A and B, i.e., the max () perform can entry the personal members of two lessons.  

Implementing by means of a way of one other class

A category can’t entry the personal members of one other class. Equally, a category can’t entry its protected members of a category. We want a good friend class on this case. 

A good friend class is used when we have to entry personal and guarded members of the category through which it has been declared as a good friend. It is usually attainable to declare just one member perform of one other class to be a good friend. 

Declaration of good friend class

class class_name
{
      good friend class friend_class;// declaring good friend class
};
class friend_class
{
};

All capabilities in friend_class are good friend capabilities of class_name.

A easy instance of a good friend class:

Code:

#embody <iostream>
utilizing namespace std;
class A
{
   int x=4;
   good friend class B; //good friend class
};
class B
{
   public:
   void show (A &a)
     {
        cout<<”worth of x is:” <<a.x;
     }
};
int principal ()
{
   A a;
   B b;
   b. show (a);
    return 0;
}

Output:

          worth of x is:4     

Implementing a world perform

Code:

#embody<iostream>
utilizing namespace std;
class area
{
    int x;
    int y;
    int z;
    public:
    void setdata (int a, int b, int c);
    void show(void);
     good friend void operator- (area &s);
};
void area ::setdata (int a, int b, int c)
{
    x=a; y=b; z=c;
}
void area::show(void)
{
    cout<<x<<" "<<y<<" "<<z<<"n";
}
void operator- (area &s)
{
    s.x =- s.x;
    s.y =- s.y;
    s.z =- s.z;
}
int principal ()
{
    area s;
    s. setdata (5,2,9);
    cout<<"s:";
    s. show ();
    -s;
    cout<<"-s:";
    s. show ();
    return 0;
}

Output:

            s: 5 2 9                                                  

      -s: -5 -2 -9 

Within the above instance operator- is the good friend perform globally declared on the scope of the category.

Good friend Class in C++

What’s a Good friend class in C++?

Good friend Class is a category that may entry each personal and guarded variables of the category through which it’s declared as a good friend, identical to a good friend perform. Courses declared as pals to another class may have all of the member capabilities as good friend capabilities to the good friend class. Good friend capabilities are used to hyperlink each these lessons.

Good friend Class in C++ Syntax:

class One{
<few strains of code right here>
good friend class Two;
};
class Two{
<few strains of code>
};

Word : Until and till we declare, class friendship is neither mutual nor inherited.

To make you perceive intimately:

  • If class A is a good friend of sophistication B, then class B just isn’t a good friend of sophistication A.
  • Additionally, if class A is a good friend of sophistication B, after which class B is a good friend of sophistication C, class A just isn’t a good friend of sophistication C.
  • If Base class is a good friend of sophistication X, subclass Derived just isn’t a good friend of sophistication X; and if class X is a good friend of sophistication Base, class X just isn’t a good friend of subclass Derived. 

Benefits of good friend perform in C++

  • Good friend perform in c++ present a level of freedom within the interface design choice
  • A good friend perform is used to entry all the personal members of a category.
  • You should use a good friend perform to bridge two lessons by working objects of two completely different lessons.
  • It will increase the flexibility of overloading operators.
  • It enhances encapsulation. Solely the programmer who has entry to the category’s supply code could make a perform good friend to that class.
  • Chances are you’ll declare a member perform of a category as a good friend of one other class.
  • It really works symmetrically with all its pals.

Abstract of C++ Good friend Perform

  • Despite the fact that the prototypes for good friend capabilities seem within the class definition, pals should not members capabilities.
  • We are able to declare good friend capabilities anyplace in a category definition, that’s both in public, personal or protected sections.
  • We are able to do good friend declarations anyplace in a category definition, i.e. both in public, personal or protected sections.
  • Violates the info hiding precept of lessons, so we must always keep away from it as a lot as attainable. You possibly can grant friendship however not take it, i.e., for sophistication B to be a good friend of sophistication A, class A should explicitly declare that class B is its good friend. The friendship relation is neither symmetric nor transitive. Good friend relationship can’t be inherited.

This brings us to the top of the weblog on Good friend capabilities in C++. Hope this lets you up-skill your C++ abilities. Additionally, in case you are making ready for Interviews, take a look at these Interview Questions for C++ to ace it like a professional.

FAQs


What’s the good friend perform in C++?

In C++, a perform that has entry to a category’s personal, protected, and public members is known as a good friend perform. Inside the class’s physique, the good friend key phrase is used to declare the good friend perform.

What’s good friend perform with instance?

In C++, a good friend perform is a singular perform that, though not being a member of a category, has the flexibility to entry secret and guarded information. Utilizing the time period “good friend” inside the category, a good friend perform is a non-member perform or common perform of a category that’s specified as a good friend.

What are some great benefits of the good friend perform in C++?

A number of the benefits of the good friend perform in c++ are
1. It allows a non-member perform to share confidential class data.
2. It makes it easy to entry a category’s personal members.
3. It’s often used when two or extra lessons embody members which can be linked to different programme components.
4. It allows the creation of simpler code.
5. It gives further capabilities that the category doesn’t sometimes use.
6. It permits a non-member perform to share confidential class data.

What are the restrictions of good friend perform?

The main drawback of good friend capabilities is that they occupy the utmost dimension of the reminiscence and may’t do any run-time polymorphism ideas.

Related Articles

Latest Articles