0% found this document useful (0 votes)
10 views

Example

Operator overloading allows modifying the default meaning of operators like +, -, *, / for user-defined data types. For example, adding two complex numbers can be done by overloading the + operator to return a complex number with the summed real and imaginary parts. Friend classes and functions can access private and protected members of other classes they are declared as friends in.

Uploaded by

deepak.bhende
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Example

Operator overloading allows modifying the default meaning of operators like +, -, *, / for user-defined data types. For example, adding two complex numbers can be done by overloading the + operator to return a complex number with the summed real and imaginary parts. Friend classes and functions can access private and protected members of other classes they are declared as friends in.

Uploaded by

deepak.bhende
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

What is operator overloading?

Operator Overloading is a very essential element to perform the operations on user-defined


data types. By operator overloading we can modify the default meaning to the operators
like +, -, *, /, <=, etc.

For example -

The following code is for adding two complex number using operator overloading-

class complex{
private:
float r, i;
public:
complex(float r, float i){
this->r=r;
this->i=i;
}
complex(){}
void displaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
return complex(r+c.r, i+c.i);
}
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}

What do you know about friend class and friend function?

A friend class can access private, protected, and public members of other classes in which it
is declared as friends.

Like friend class, friend function can also access private, protected, and public members.
But, Friend functions are not member functions.

For example -

class A{
private:
int data_a;
public:
A(int x){
data_a=x;
}
friend int fun(A, B);
}
class B{
private:
int data_b;
public:
A(int x){
data_b=x;
}
friend int fun(A, B);
}
int fun(A a, B b){
return a.data_a+b.data_b;
}
int main(){
A a(10);
B b(20);
cout<<fun(a,b)<<endl;
return 0;
}

You might also like