hello, i made an int variable named "My_var"
i want to acces to it from all my classes, how can i do ?
Printable View
hello, i made an int variable named "My_var"
i want to acces to it from all my classes, how can i do ?
you'll need to extern it to every file that will use it:
in file1.cpp
int My_Var;
if file2.cpp that will use My_Var
extern int My_Var;
miked
Hi
Make it global, i.e. declare it outside any class in a .h file or in a dedicated .h file. Place extern int MyVar in cpp file where you need this variable. Or place this statement in a dedicated .h file. You must only be sure that you DECLARE your variable once.
HTH
Yves Le Sant
Metrology and Measurement Unit
Fundamental and Experimental Aerodynamics Departement
ONERA Meudon
(Office National d'Etudes et de Recherches Aérospatiales)
FRANCE
The extern keyword does not redefine the variable. It tells the compiler to look elsewhere for the variable declaration. One more item about global variables: if you have a local variable of the same name, then within that function calling that name will refer to the local variable. To access the global variable use the scope resolution operator ::. If you always use the scope resolution operator to access a global then you can easily identify globals in your code.
In file pair MyClass1.cpp/MyClass1.h:
int nMyInt; // global variable
void MyFunction()
{
int nMyInt; // local variable
nMyInt = 1; // assign 1 to local variable
::nMyInt = 2; // assign 2 to global variable
}
In file pair MyClass2.cpp/MyClass2.h:
extern int nMyInt;
thank you all, it's a very good help