c++classscopemember-access

Class private member wont change in function



using namespace std;

class map
{
    private:
        float result= 0;
    public:
        void func_1();
        void setres(float counter);
        float getres();
};
void map::setres(float counter)
{
    result= counter;
}
float map::getres()
{
    return result;
}
void map::func_1()
{
    float num_0=0, num_1=0, sum=0, i;
    
    map run;
    
    cout << run.getres() << " Result." << endl;
    if(result != 0)
        cout << "We already have a result saved and it's: " << run.getres() << endl;
    else
    {
        cout << "Give me first number: ", cin >> num_0;
        cout << "Give me second number: ", cin >> num_1;
        sum= num_0+num_1;
        cout << "Result is: " << sum << endl;
    }
    cout << "The program will save the result." << endl;
    run.setres(sum);
    cout << "The saved result is: " << run.getres() << "\nPress 1 to repeat the function and check\nif the result is saved." << endl;
    cin >> i;
    if(i==1)
        run.func_1();    
}

int main()
{
    map go;
    go.func_1();
    return 0;
}

I don't know why the private variable result is not saved. And how can i make it work.

Then i start compiling it works fine, private result is changing, but then i reopen the function, the result is back to 0 and i wanted it ro be the last result.

Example: I put 4 I put 7 Sum is 11 And saved result is 11 Then i press 1 to go to the start the result is 0 again, but i wanted it to be 11 not 0.


Solution

  • Within the function you are creating a local variable of the type map

    map run;
    

    the data member result of which is changed. That is the function does not change the data member result of the object for which the function is called.

    Moreover for example in this code snippet

    cout << run.getres() << " Result." << endl;
    if(result != 0)
    

    you are accessing the data member result of two different object. In the first statement

    cout << run.getres() << " Result." << endl;
    

    you are accessing the data member of the local object run while in the next statement

    if(result != 0)
    

    you are accessing the data member result of the object (the object go declared in main) for which the member function is called.

    So remove the declaration in the function

    map run;
    

    and instead of expressions like for example run.getres() use either just getres() or this->getres().