Private accessing fail..

I just wanted to know why ( double answer ) is not working
it just give me the garbage numbers instead of adding
here is the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>

using namespace std;
class Addition{
public:
    void setAnswer (double x, double y){
    double answer = x + y;

    }
    double getAnswer (){
    return answer;
    }
private:
    double answer;
};


int main()
{
    double a, b;
    cout << "Please enter a number: ";
    cin >> a;
    cout << endl;
    cout << "Please enter a number: ";
    cin >> b;
    Addition calc;
    calc.setAnswer(a, b);
    cout << calc.getAnswer();

    return 0;
}
You're defining a different answer locally inside your setAnswer member function.
Change line 7 to just answer = x + y;

(This is the same as doing this->answer = x+y;)
Last edited on
Fair Enough,

Sorry I am too new for this things..

Thanks brother, You taught me a great thing... <3
Topic archived. No new replies allowed.