Sorry jonnin, I was actually replying to the post above yours, as I hadn't seen yours at that point.
Yeah, the original code (as per the first example) is just copied from the original problem, so it's not my code. I'm not sure it's meant to be especially good code, rather code designed to trick people a little doing the quiz.
Okay, so I can see that your code outputs 2, (which is what I figured it should be), and you've changed the static int to a plain old int, and it works just fine. I also note Repeater's code (thx), where he defines "a" outside of the class with "int ABC::a;" which also works. However …. (excuse my ignorance!) …
… and going back to a slightly modified version of the first piece of code, and now I create an object, I'd have still expected z to be 2, but it isn't. How come? After all, z starts life at 1, and creating the object surely invokes the constructor which then increments z by 1, so (in my beginners mind) it should be 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
using namespace std;
int z=1;
class ABC {
public:
int a;
ABC(){a=1; z++;}
};
int main(void) {
ABC obj();
cout << z << endl;
return 0;
}
|
Also, just curious; so you got rid of the "static" from the "a" variable in the class, and it works just fine; and you didn't need to create the variable anywhere else. The other poster instead maintained it as a static variable but then declared it outside of the class, and that also worked. When you declare a variable as static in that way, in a class, must you always then define it elsewhere too?
I really appreciate your time and effort. Thanks!