Search code examples
c++classoopfriend-function

C++ friend function not working


I am new to C++ and have been trying to get my head around classes in c++. Recently I tried out this program and instead of returning an integer 9, it returns some garbage value. Can someone please help me out

#include <iostream>
#include <cstring>
#include <math.h>
using namespace std;
class abc;
class xyz
{
    int a;
public:
    friend int add(xyz, abc);
    friend void setval(xyz, int, abc, int);


};
class abc
{
    int b;
public:
    friend int add(xyz, abc);
    friend void setval(xyz, int, abc, int);
};

int add(xyz V1, abc V2)
{ return (V1.a + V2.b);}
void setval(xyz v1, int v11, abc v2, int v22)
{v1.a = v11; v2.b = v22; }

int main()
{
    xyz A;
    abc B;
    setval(A, 4, B, 5);
    cout<<add(A, B)<<endl;
    return(0);
}

Solution

  • This is happening because you are passing the arguments to setval function by value which will modify the copy of the object that you have passed.

    Use the following signature instead:

    void setval(xyz& v1, int v11, abc& v2, int v22);
    

    This way you will be sending the reference to your objects instead of copies of those objects made in some separate blobs of memory. Thus, the objects created in your main function will be assigned the values.