friend functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream.h>
#include<conio.h>

class complex
{
      int r;
      public:
             void input(int a)
             {r=a;}
             void change1()
             {r=1;}
             void print()
             {cout<<r;}
             friend void change2(complex);
};

void change2 (complex A)
{A.r=2;}

int main()
{
    complex A;
    A.input(3);
    A.change1();
    change2(A);
    A.print();
    getch();
}


should not the output be 2. But it is coming out to be 1!!
When you are passing your object into the function, you are actually passing a copy of the object. You need to pass by reference like so:

1
2
void change2 (complex &A)
{A.r=2;}

This will pass a reference to the object so that you can modify the original instead of modifying a copy that is destroyed at the end of the function's scope.
oh yea..thnx
Topic archived. No new replies allowed.