Question

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);
}
Was it helpful?

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.

OTHER TIPS

friend void setval(xyz, int, abc, int);

Your set functions sets value to an copy of the passed object not the passed object. You need to pass by reference.

friend void setval(xyz &, int, abc &, int);
                   ^^^^^^      ^^^^^^ 

I may as well suggest starting with a good book:
The Definitive C++ Book Guide and List

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top