Home > Net >  Can I set a value using a function in a class?
Can I set a value using a function in a class?

Time:11-18

If I have a friend function can I somehow use set() to assign a value to a private variable inside the function? Or some other method?

Example : Here I have 3 private variables. I tried to make the sum of 2 of them and store the result in the 3rd one. I tried to do it with a setter but the result is 0. In main it works, but I don't know if I can make it work in the class function.

#include <iostream>
using  namespace std;

class Function{
private:
    int a;
    int b;
    int sum;

public:
    Function() = default;
    Function(int _a, int _b);
    friend int sumNumber(Function f);
    
    //Setter and getter
    int getA() const;
    void setA(int a);
    int getB() const;
    void setB(int b);
    int getSum() const;
    void setSum(int sum);
};

Function::Function(int _a, int _b) {
    this->a = _a;
    this->b = _b;
}
int Function::getA() const {
    return a;
}
void Function::setA(int a) {
    Function::a = a;
}
int Function::getB() const {
    return b;
}
void Function::setB(int b) {
    Function::b = b;
}
int Function::getSum() const {
    return sum;
}
void Function::setSum(int sum) {
    Function::sum = sum;
}



int sumNumber(Function f) {
    int a = f.getA();
    int b = f.getB();
    int sum = a   b;
    f.setSum(sum);
    return sum;
};



int main() {
Function AA(1,2);
cout << sumNumber(AA);
cout << " " << AA.getSum();

AA.setSum(sumNumber(AA));
cout << "\n" << AA.getSum();
    return 0;
}

Output :

3 0
3

CodePudding user response:

As alluded to in the comments, the issue is with this function:

int sumNumber(Function f) {
    int a = f.getA();
    int b = f.getB();
    int sum = a   b;
    f.setSum(sum);
    return sum;
};

Let us walk through your code:

Function AA(1,2);

You create a object of type Function, called AA and you allocate each member variable of that object via the constructor (1 and 2).

cout << sumNumber(AA);

You call your method (sumNumber) and pass to it a copy of your variable AA. That function adds the two numbers together and internally calls setSum.

cout << " " << AA.getSum();

You now try to display the sum value by calling the getSum method. But the issue was that you passed a copy of your variable into the sumNumber function. The original AA variable was left alone.


To fix this you need to adjust your function by adding an ampersand &. Like this:

int sumNumber(Function& f) {
    int a = f.getA();
    int b = f.getB();
    int sum = a   b;
    f.setSum(sum);
    return sum;
};

Now your variable AA is being passed by reference and not by value. There are lots of tutorials about this concept.

  • Related