Hi, I am trying to make a simple program with a "House" class to learn how to use static members of a class. The idea is to get numberOfHouses to equal 2, and be a variable shared between house1 and house2, but I keep getting a compiler error that I cannot resolve. Help is appreciated, thank you!
#include <iostream>
usingnamespace std;
class House {
private:
staticint numberOfHouses; //number of houses there are total
int houseSize; //int from 1 to 10
int occupants;
int maxOccupants;
public:
House() {
maxOccupants = 4;
occupants = 1;
houseSize = 1;
++numberOfHouses;
}
staticint getnumOfHouses() {return numberOfHouses;}
};
int main() {
House house1;
House house2;
cout << "The number of houses I have created is..." << House::getnumOfHouses() << ".\n";
return 0;
}
Undefined symbols for architecture x86_64:
"House::numberOfHouses", referenced from:
House::getnumOfHouses() in main-902b06.o
House::House() in main-902b06.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Well initializing a variable outside of a class doesn't necessarily mean it's in the global namespace. Though, probably 99% of the time it will be. I still wouldn't call initializing a static variable in the global namespace a global variable.