@dhayden the extern int age should reside both in the main file and in the class? |
Sort of. This gets to the difference between
declaring a variable and
defining it. When you declare a variable, you tell the compiler the variable's name and type. When you define a variable, you also tell the compiler to allocate memory for it. Most of the time, you define variables:
int myint=4;
You can declare a variable by adding extern, and by NOT giving it a value:
extern int myint;
It's important to understand that you can declare a variable any number of times in any number of files, but you can only define it once. This makes sense if you think about it: you have to tell the compiler to allocate space for the variable once, but you can tell "hey, there's a variable called myint" as many times as you want.
So why would you do this? For the exact problem you're facing! When you need access to the same variable in two different files. In that case, you can define the variable in one file, and they declare it in the other(s).
Usually there are several variables and classes that you need to declare, so the declaration goes in a header file and you can #include the file whereever you need it:
animals.h:
1 2 3 4 5
|
class Animals {
....
};
extern int number_of_animals;
|
animals.cpp:
1 2 3 4 5 6 7
|
#include "animals.h"
int number_of_animals; // define number_of_animals
void f()
{
std::cout << number_of_animals;
}
|
main.cpp
1 2 3 4 5
|
#include "animals.h"
int main()
{
std::cout << number_of_animals;
}
|
Note that this is all for illustration. It would be better to use one of the standard containers to store your animals and use the container's size() method to get the number of animals.