I want to assign a value to the variable x which belongs to the class X using friend function.

Is there any way to assign a value, say 30 to the variable x using the friend function.

I tried the following code but the output is different.

#include <iostream>
#include <conio>

class X
{
int x;
public:
void showdata()
{
cout<<"x ="<<x<<endl;
}
friend void putvalue(X a);
};
void putvalue(X a)
{
a.x=30; //
}

int main()
{
X test;
putvalue(test);
test.showdata();
getch();
return 0;
}

This is your problem:

void putvalue(X a)
{
    a.x=30; //
}

You're passing a by value, not by reference, so when you pass test to putvalue , you're actually modifying a copy of test , not the original object itself, and your modified copy gets lost when putvalue returns.

You can do it with a pointer:

class X
{
    int x;
public:
    void showdata()
    {
        cout << "x =" << x << endl;
    }

    friend void putvalue(X* a);
};

void putvalue(X* a)
{
    a->x = 30;
}

int main()
{
    X test;
    putvalue(&test);
    test.showdata();
    getch();
    return 0;
}

You can do it with a reference:

class X
{
    int x;
public:
    void showdata()
    {
        cout << "x =" << x << endl;
    }

    friend void putvalue(X& a);
};

void putvalue(X& a)
{
    a.x = 30;
}

int main()
{
    X test;
    putvalue(test);
    test.showdata();
    getch();
    return 0;
}

**what is the difference between :

friend void putvalue(X* a); AND

friend void putvalue(X& a);

please help...

This article has been dead for over six months. Start a new discussion instead.