Value define problem in class function

Hi,

I have a class:
1
2
3
4
5
6
7
8
9
10
11
12
class testa {
public:
   int n;
   double s;

   void funca();
}
void funca() {
   n = 500;
   s = 1.0/n;
   cout << s << endl;
}

The value of s should be 0.002. However, it's in reality 0. Could anyone please tell me why? Thanks!
Last edited on
It shouldn't even compile:
a) you forgot semicolon after class declaration
b) You are defining class members wrong. it should be void testa::funca() {

Works fine for me: http://ideone.com/1RAyXk
Sorry for the errors. Actually there are two functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class testa {
public:
   int n;
   double s;

   void funca();
   void funcb();
};
void testa::funca() {
   n = 500;
}
void testa::funcb() {
   s = 1.0/n;
   cout << s << endl;
}
int main()
{
   testa x;
   x.funca();
   x.funcb();
}

It doesn't work on my machine. Could anyone please tell me why?
Last edited on
Try to build from scratch. This code is correct and shall work.
It seems I found the problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class testa {
public:
   int n;
   double s;

   void funca();
   void funcb();
};
void testa::funca() {
   n = 500;
}
void testa::funcb() {
   double s = 1.0/n;
   cout << s << endl;
}
int main()
{
   testa x;
   x.funca();
   x.funcb();
}

In function funcb() if I add type double before s, it doesn't work. Without the type name, it works. Could anyone tell me why? Double definition cannot work?
it still should work (output 0.002) but class variable s will not change: you are declaring local variable which shadows class member.
So, if I modify the code as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class testa {
public:
   int n;
   double s;

   void funca();
   void funcb();
};
void testa::funca() {
   n = 500;
}
void testa::funcb() {
   double s = 1.0/n;
}
int main()
{
   testa x;
   x.funca();
   x.funcb();
   cout << s << endl;
}
It surely won't work, right? How is it possible that double s = 1.0/n; could shadow the class variable s? They have the same name and void testa::funcb() is a member of the class. ?
s inside funcb() is function local. You will got an error on line 20. because there is no variable s in current context (you should use x.s)
Topic archived. No new replies allowed.