Please see the C++ code fragment below:
#include .....
Class1 class1;
Class2 class2;
...
void Class3::foo() {
...
}
What are the variables: class1 and class2? Are they global variables? Static variables? What actually are these? In C++ OO programming, is it good practice to use these because any member function of any class in the file can access them?
Sorry for the beginner’s question.
Thanks.
Yes class1 & class2 are global variables.
What are global variables?
Variables declared outside of a block are called global variables. Global variables have program scope, which means they can be accessed everywhere in the program, and they are only destroyed when the program ends.
Because global variables have program scope, they can be used across multiple files. In order to use a global variable that has been declared in another file, you have to use a forward declaration or a header file, along with the
externkeyword. Extern tells the compiler that you are not declaring a new variable, but instead referring to a variable declared elsewhere.In C++ OO programming, is it good practice to use these because any member function of any class in the file can access them?
Typically, people use global variables because:
But Global variables are evil!!
Why?
For the simple reason that they increase the complexity of a program by manyfolds.
It is difficult to keep track of a global variable getting modified, simply because it can be modified anywhere across any of the multiple files.
In multithreaded programs, multiple threads can race to acquire these global variables, So these global’ s should always be protected through some sort of an synchronization mechanism. Typically, it is hard to understand and write such mechanism unless you understand the entire system.
Since you asked,
What are Static variables?
static variables are variables which will be qualified by the keyword
static.How are static variables different from global variables?
An important differentiating point to be considered:
Scope:
Scope of the object is whether the object is visible(known by its name) at this position where it is being accessed..
Static variables are local to the block in which they are defined, while global variables are accessible across any file across the program.