I am new to OOP. Before I did my best never to use global variables and it worked fine. But with OOP I find that I am starting to use global variables... very frustrating indeed. How do you prevent it? Let me give you an example.

Assume you have a class called World. It has a wide range of variables and functions that operate on those variables.

World W1;


If this function call uses other functions local to the World class and changes variables (lets say temperatures in the World), you find your self in a situation where functions inside world uses global variables (global inside World).

With smaller classes I have no problem but when it gets big like this, I find myself using tons of global variables... :-(

Should you pass World variables as arguments between functions inside World perhaps??

Any input is very welcome! Thanks!!

Recommended Answers

All 3 Replies

class variables do not have to be passed as parameters to class methods because the methods already have full access to them.

Post an example of why you think you need global variables.

If they are member variables of the class, they are not global. They are, as you note, accessible to all functions of the class. However, they are accessible only within a given instance of the class.

If you have a variable temperature in class World, and you have multiple worlds created (w1, w2, etc), each world's temperature is "local" to that instance. That is, w1.temperature is not the same as w2.temperature.

In dealing with your class's functions, parameters will primarily be the inputs to the functions, or sometimes reference parameters to allow the function to communicate state of the variables to the user.

(note: if you make a class member static, the game changes, but that's another discussion.)

Thanks guys for your comments! I was just making sure I was not violating an OOP 101 rule or antything like that.

To clarify, with global I meant local to the class. It is just that my biggest class has tons of parameters and quite a few functions local to it. I am not used to have functions that operate on variables that are not passed as arguments. It feels like they are global which in a way they are.

I always thought that the bad thing about global variables was that their values can be changed in places where you least expect it. That would be the case for me too if I didn't pay close attention to what I am doing as no arguments are passed between the World functions. Without a World class, all my functions would have many arguments and it would be easier to some extent to track where something could be changed.

Anyway, you helped me understand OOP better and I thank you for your inputs!!


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.