Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8f3dcc3

Browse files
implementing overloading using friend functions
1 parent 58230ac commit 8f3dcc3

File tree

1 file changed

+52
-0
lines changed
  • Learn_CPP_Programming_Deep_Dive/Section 12 Operator Overloading/Operator_overloading_through_friend_functions

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
/* -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
6+
In C++, a friend function is a function that is not a member of a class but is granted special access to the private and protected members of that class.
7+
Friend functions are often used when you need to allow an external function or another class to access the private data of a class without making those data members public.
8+
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
9+
10+
class Complex
11+
{
12+
private:
13+
int real;
14+
int imaginary;
15+
public:
16+
Complex(int r=0, int i=0) : real(r), imaginary(i)
17+
{
18+
cout<<"Parameterized constructor for "<<real<<" +i* "<<imaginary<<endl;
19+
}
20+
21+
void display()
22+
{
23+
cout<<real<<" +i* "<<imaginary<<endl;
24+
}
25+
26+
friend Complex operator+(Complex c1, Complex c2); // this friend function is not a member function of the class , but it can access all members of the class, including private or protected without need to change them to public
27+
};
28+
29+
30+
Complex operator+(Complex c1, Complex c2)
31+
{
32+
Complex temp;
33+
temp.real = c1.real +c2.real;
34+
temp.imaginary = c1.imaginary +c2.imaginary;
35+
36+
temp.display();
37+
return temp;
38+
39+
}
40+
41+
int main(void)
42+
{
43+
Complex c1(5,3),c2(5,7),c3,c4;
44+
45+
c3 = operator+(c1,c2);
46+
c3.display();
47+
48+
c4 = c1 + c2;
49+
c4.display();
50+
51+
return 0;
52+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /