class Rectangle {
public:
double x, y, width, height;
public:
int id;
protected:
staticunsignedint count;
//----------------------------
public: // CONSTRUCTOR
Rectangle(double x, double y, double width, double height): x(x), y(y), width(width), height(height) {
id = Rectangle::count++;
cout << "Constructing Rectangle at position: (" << x << ", " << y << ")" << endl;
}
//----------------------------
public: // DESTRUCTOR
~Rectangle() {
cout << "Destructing Rectangle: " << id << endl;
}
};
I get the following error:
obj\Debug\main.o||In function `Rectangle':|
[color=red]C:\Users\Barliesque\Documents\C++\First Project\main.cpp|33|undefined reference to `Rectangle::count'|
C:\Users\Barliesque\Documents\C++\First Project\main.cpp|33|undefined reference to `Rectangle::count'|[/color]
||=== Build finished: 2 errors, 0 warnings ===|
I just don't get it. count is statically defined to the class, but I can't refer to it???
Another problem I'm having: I wanted to set id to be a const so that it can't be changed after it's set in the constructor, but if it's a const I can't initialize it at all without getting compiler errors that I'm trying to modify a constant.
I've consulted several reference materials, and as far as I can tell, I'm doing exactly what needs to be done. I'm getting worn out reading and reading but not finding an answer to me specific questions, hence I've turned to the forums.
My understanding was that a variable defined using const could be assigned a value once and only once. But the errors that resulted suggest I can only assign a literal value when the const is declared. Is that the case?
The static member has to be defined outside the class as weel as declared inide the class.
So somewhere in one of your cpp files - put unsignedint Rectangle::count
or unsignedint Rectangle::count = initial value
Constant member have to be initialised in the constructor initialisation list. (although static constant members that are integral types can be initialised in the class declaration).
That's all I needed. Thank you for putting me out of my misery. :)
I don't know why it was so difficult to find out these simple rules from the reference materials. I've probably got some un-learning of other OOP languages to do. Having to declare statics outside the class just looks odd and redundant, but I'll get used to it!