Introduction
In the world of object-oriented programming, encapsulation stands as a beacon of safe and structured code creation. C++ additional elevates this precept by introducing a strong but even handed function: the buddy operate, which adeptly navigates the positive line between sustaining encapsulation and permitting managed entry to class members. This exceptional instrument, which might entry the personal and guarded members of a category, presents programmers the next diploma of flexibility and effectivity in code growth. In the midst of preserving the sanctity of knowledge encapsulation, it facilitates a seamless interplay between courses, fostering a symbiotic relationship that may improve the general performance of a software program system.
In this tutorial, we are going to discover ways to create a buddy operate in C++ with the assistance of some examples.
Data hiding is a basic idea in object-oriented programming, and it restricts the entry of personal members from exterior the category.
What is a Friend Function in C++?
A buddy operate in C++ is outlined as a operate that may entry personal, protected, and public members of a category.
The buddy operate is asserted utilizing the buddy key phrase contained in the physique of the category.
Friend Function Syntax:
class className {
... .. ...
buddy returnType functionName(arguments);
... .. ...
}
By utilizing the key phrase, the ‘friend’ compiler understands that the given operate is a buddy operate.
We declare a buddy operate contained in the physique of a category, whose personal and protecting knowledge must be accessed, beginning with the key phrase buddy to entry the info. We use them when we have to function between two completely different courses on the identical time.
What is Friend Function?
Friend capabilities of the category are granted permission to entry personal and guarded members of the class in C++. They are outlined globally exterior the category scope. Friend capabilities will not be member capabilities of the category. So, what precisely is the buddy operate?
A buddy operate in C++ is a operate that’s declared exterior a category however is able to accessing the personal and guarded members of the category. There might be conditions in programming whereby we wish two courses to share their members. These members could also be knowledge members, class capabilities or operate templates. In such circumstances, we make the specified operate, a buddy to each these courses which is able to enable accessing personal and guarded knowledge of members of the category.
Generally, non-member capabilities can’t entry the personal members of a specific class. Once declared as a buddy operate, the operate is ready to entry the personal and guarded members of those courses.
Upskill with different Programming languages
User-defined Function varieties
Friend capabilities in C++ have the next varieties
- Function with no argument and no return worth
- Function with no argument however with return worth
- Function with argument however no return worth
- Function with argument and return worth
Declaration of a buddy operate in C++
class class_name
{
buddy data_type function_name(arguments/s); //syntax of buddy operate.
};
In the above declaration, the key phrase buddy precedes the operate. We can outline the buddy operate anyplace in this system like a traditional C++ operate. A category’s operate definition doesn’t use both the key phrase buddy or scope decision operator (: 🙂.
Friend operate is named as function_name(class_name) and member operate is named as class_name. function_name.
Use of Friend operate in C++
As mentioned, we require buddy capabilities each time we now have to entry the personal or protected members of a category. This is just the case when we don’t need to use the objects of that class to entry these personal or protected members.
To perceive this higher, allow us to contemplate two courses: Tokyo and Rio. We would possibly require a operate, metro(), to entry each these courses with none restrictions. Without the buddy operate, we would require the thing of those courses to entry all of the members. Friend capabilities in c++ assist us keep away from the state of affairs the place the operate needs to be a member of both of those courses for entry.
Important C++ Topics to Know
C++ operate overloading
Two capabilities can have the identical identify if the quantity and kind of argument handed is completely different. Functions which have the identical identify , however have completely different arguements are referred to as Overloading capabilities.
Friend capabilities are additionally utilized in operator overloading. The binary operator overloading in c++ utilizing the buddy operate could be achieved as defined under.
Binary operator overloading in C++ utilizing Friend operate
The operator overloading operate precedes a buddy key phrase on this method. It additionally declares a operate class scope. The buddy operator operate takes 2 parameters in a binary operator. It then varies one parameter in a unary operator.
The operate will likely be carried out exterior the category scope. But, the working and the implementation are the identical because the binary operator operate.
If you need to construct your data in C++, contemplate getting licensed. This Introduction to C++ Free Course will enable you to be taught the required expertise and in addition a certificates on completion that may be added to your social profiles. You also can take a look at our Full Stack Program by IIT Roorkee.
Characteristics of Friend Function in C++
- The operate shouldn’t be within the ‘scope’ of the category to which it has been declared a buddy.
- Friend performance shouldn’t be restricted to just one class
- Friend capabilities is usually a member of a category or a operate that’s declared exterior the scope of sophistication.
- It can’t be invoked utilizing the thing as it’s not within the scope of that class.
- We can invoke it like several regular operate of the category.
- Friend capabilities have objects as arguments.
- It can’t entry the member names straight and has to make use of dot membership operator and use an object identify with the member identify.
- We can declare it both within the ‘public’ or the ‘private’ half.
- These are a few of the buddy capabilities in C++ traits
Implementing Friend Functions
Friend Functions could be carried out in two methods:
A technique of one other class:
We declare a buddy class once we need to entry the personal knowledge members of a specific class.
A Global operate:
A ‘global friend function’ permits you to entry all of the personal and guarded members of the worldwide class declaration.
A easy instance of a C++ buddy operate used to print the size of the field.
Code:
#embrace <iostream>
utilizing namespace std;
class Box
{
personal:
int size;
public:
Box (): size (0) {}
buddy int printLength (Box); //buddy operate
};
int printLength (Box b)
{
b. size +=10;
return b. size;
}
int foremost ()
{
Box b;
cout <<” Length of field:” <<printLength (b)<<endl;
return 0;
}
Output:
Length of field:10
Simple instance when the operate is pleasant for 2 courses.
Code:
#embrace<iostream>
utilizing namespace std;
class B; //ahead declaration.
class A
{
int x;
public:
void setdata (int i)
{
x=i;
}
buddy void max (A, B); //buddy operate.
} ;
class B
{
int y;
public:
void setdata (int i)
{
y=i;
}
buddy 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 foremost ()
{
A a;
B b;
a. setdata (10);
b. setdata (20);
max (a, b);
return 0;
}
Output:
20
In the above instance, max () operate is pleasant to each class A and B, i.e., the max () operate can entry the personal members of two courses.
Implementing by way of a technique of one other class
A category can’t entry the personal members of one other class. Similarly, a category can’t entry its protected members of a category. We want a buddy class on this case.
A buddy class is used when we have to entry personal and guarded members of the category wherein it has been declared as a buddy. It can also be potential to declare just one member operate of one other class to be a buddy.
Declaration of buddy class
class class_name
{
buddy class friend_class;// declaring buddy class
};
class friend_class
{
};
All capabilities in friend_class are buddy capabilities of class_name.
A easy instance of a buddy class:
Code:
#embrace <iostream>
utilizing namespace std;
class A
{
int x=4;
buddy class B; //buddy class
};
class B
{
public:
void show (A &a)
{
cout<<”worth of x is:” <<a.x;
}
};
int foremost ()
{
A a;
B b;
b. show (a);
return 0;
}
Output:
worth of x is:4
Implementing a world operate
Code:
#embrace<iostream>
utilizing namespace std;
class area
{
int x;
int y;
int z;
public:
void setdata (int a, int b, int c);
void show(void);
buddy 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 foremost ()
{
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
In the above instance operator- is the buddy operate globally declared on the scope of the category.
Friend Class in C++
What is a Friend class in C++?
Friend Class is a category that may entry each personal and guarded variables of the category wherein it’s declared as a buddy, identical to a buddy operate. Classes declared as mates to some other class may have all of the member capabilities as buddy capabilities to the buddy class. Friend capabilities are used to hyperlink each these courses.
Friend Class in C++ Syntax:
class One{
<few strains of code right here>
buddy class Two;
};
class Two{
<few strains of code>
};
Note : Unless and till we declare, class friendship is neither mutual nor inherited.
To make you perceive intimately:
- If class A is a buddy of sophistication B, then class B shouldn’t be a buddy of sophistication A.
- Also, if class A is a buddy of sophistication B, after which class B is a buddy of sophistication C, class A shouldn’t be a buddy of sophistication C.
- If Base class is a buddy of sophistication X, subclass Derived shouldn’t be a buddy of sophistication X; and if class X is a buddy of sophistication Base, class X shouldn’t be a buddy of subclass Derived.
Advantages of buddy operate in C++
- Friend operate in c++ present a level of freedom within the interface design possibility
- A buddy operate is used to entry all the personal members of a category.
- You can use a buddy operate to bridge two courses by working objects of two completely different courses.
- It will increase the flexibility of overloading operators.
- It enhances encapsulation. Only the programmer who has entry to the category’s supply code could make a operate buddy to that class.
- You could declare a member operate of a category as a buddy of one other class.
- It works symmetrically with all its mates.
Summary of C++ Friend Function
- Even although the prototypes for buddy capabilities seem within the class definition, mates will not be members capabilities.
- We can declare buddy capabilities anyplace in a category definition, that’s both in public, personal or protected sections.
- We can do buddy declarations anyplace in a category definition, i.e. both in public, personal or protected sections.
- Violates the info hiding precept of courses, so we must always keep away from it as a lot as potential. You can grant friendship however not take it, i.e., for sophistication B to be a buddy of sophistication A, class A should explicitly declare that class B is its buddy. The friendship relation is neither symmetric nor transitive. Friend relationship can’t be inherited.
This brings us to the tip of the weblog on Friend capabilities in C++. Hope this lets you up-skill your C++ expertise. Also, if you’re getting ready for Interviews, take a look at these Interview Questions for C++ to ace it like a professional.
FAQs
What is the buddy operate in C++?
In C++, a operate that has entry to a category’s personal, protected, and public members is known as a buddy operate. Within the category’s physique, the buddy key phrase is used to declare the buddy operate.
In C++, a buddy operate is a singular operate that, though not being a member of a category, has the flexibility to entry secret and guarded knowledge. Using the time period “friend” inside the category, a buddy operate is a non-member operate or common operate of a category that’s specified as a buddy.
Some of some great benefits of the buddy operate in c++ are
1. It permits a non-member operate to share confidential class info.
2. It makes it easy to entry a category’s personal members.
3. It is ceaselessly used when two or extra courses embrace members which might be related to different programme components.
4. It permits the creation of simpler code.
5. It presents additional capabilities that the category doesn’t usually use.
6. It permits a non-member operate to share confidential class info.
The main drawback of buddy capabilities is that they occupy the utmost measurement of the reminiscence and might’t do any run-time polymorphism ideas.