//This tut contains Friend Function in C++
/* Properties of friend functions
1. Not in the scope of class
2. since it is not in the scope of the class, it cannot be called from the object of that class. c1.sumComplex() == Invalid
3. Can be invoked without the help of any object
4. Usually contans the objects as arguments
5. Can be declared inside public or private section of the class
6. It cannot access the members directly by their names and need object_name.member_name to access any member.
*/
#include <iostream>
using namespace std;
class Complex
{
int a, b;
// Below line means that non member - sumComplex funtion is allowed to do anything with my private parts (members)
friend Complex sumcomplex(Complex o1, Complex o2);
public : void setnumber(int n1, int n2)
{
a = n1;
b = n2;
}
void printnum(void)
{
cout << "Your number is " << a << "+" << b << "i" << endl;
}
};
Complex sumcomplex(Complex o1, Complex o2)
{
Complex o3;
o3.setnumber(o1.a + o2.a, o1.b + o2.b);
return o3;
}
int main()
{
Complex c1, c2, sum;
c1.setnumber(1, 4);
c1.printnum();
c2.setnumber(2, 5);
c2.printnum();
sum = sumcomplex(c1, c2);
sum.printnum();
return 0;
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.