can i use class instance variables in functions that aren't part of the class?

can i use class instance variables in functions that aren't part of the class?
this is a simple example of my problem.

class person{
public:
person();
~person();
int height;
int weight;
};

int is_he_short(){if(tim.height<70){cout<<"he is short" }

int main(){
peron tim;
tim.height=60;
tim.weight=150;
is_he_short();}


my compiler says tim was not declared in this scope. i know that i caould make the is_he_short function a part of the person class and get rid of tim. in front of height but for what i'm doing i don't want the function part of that class. Make sense? i hope so. please respond
'tim' is local to main, so it's not visible inside of is_he_short, which is why you get the error.

You could pass 'tim' to the function as a parameter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool is_he_short(const person& who)
{
  return (who.height < 70);
}

int main()
{
  person tim;
  tim.width = 60;
  tim.height = 150;
  if( is_he_short( tim ) )
    cout << "tim is short";

  return 0;
}


But, a more intuitive way is to make is_he_short a member function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class person
{
public:
  //...

  bool is_he_short()
  {
    return (height < 70);
  }
};

int main()
{
  person tim;
  // ... set width/height

  if( tim.is_he_short() )
    cout << "tim is short";

  return 0;
}
thanks for the help... 2nd suggestion helps alot
To obtain your original desired result, you need to declare tim outside main().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//MainFile.cpp

class person
{
...
}

person tim;

bool is_he_short()
{
...
}

int main()
{
...
}


This way it should work the way you wanted to. But again, a better approach is to make is_he_short() a member function as explained by Disch. :)
will tim still work in main function?
will tim still work in main function?


In webJose's code? Yes it will, because it is declared as global variable.
Last edited on
Avoid globals. Writing a function that only works with 'tim' is bad form. It's best to take the person as a parameter, or to have it as a member function. That way your function will work with ANY person, and not just tim.

Globals lead to disorganized, hard to maintain code that is not reusable. Refrain from using them unless it's really the best option (which isn't often the case).
robman: Instead of asking "Will it work?", go ahead and actually TRY IT. :-) Put some back into the learning.

I agree with Disch that globals tend to limit and disorganize. I, however, still think that since you asked about it, you should know about it in case you need it in the future. After all, this is a forum to learn. So know about this construct (global variables), but really analyze the consequences of using them.
sry webjose i normally would but i'm away from my compiler for a few days...
Topic archived. No new replies allowed.