help with static members of a class

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!

CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

class House {
private:
	static int 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;
	}
	static int getnumOfHouses() {return numberOfHouses;}
};

int main() {
	House house1;
	House house2;
	
	cout << "The number of houses I have created is..." << House::getnumOfHouses() << ".\n";
	
	return 0;
}


COMPILER ERROR
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)

You need to initialize the static variable outside of the class.


1
2
3
	static int getnumOfHouses() {return numberOfHouses;}
};
int House::numberOfHouses = 0;


http://www.cplusplus.com/doc/tutorial/templates/
Last edited on
Oh, I see. So this is one of the few cases where a global variable is okay, then?
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.
Topic archived. No new replies allowed.