I am new to C++, though I have worked with C and Java before.
In the following code, I:
- Define the polygon class. For now it only has 1 variable: numpoints
- create a global pointer to a polygon object that's null
define a handler for a click event, which if the object exists, just prints the value of numpoints. If it doesn't, it creates it and sets the value of numpoints to be 0.
//defining polygon class class polygon{ public: int numpoints; }; //create a global pointer that's uninitialized static polygon *current = NULL; //define a click handler. void leftClick(int x, int y){ if (current==NULL){ polygon newpoly; current = &newpoly; current->numpoints = 0; printf("created new polygon\n"); printf("%i points\n", (*current).numpoints); }else{ printf("polygon exists\n"); printf("%i points\n", (*current).numpoints); } }
After the first click, the program prints
created new polygon
0 points
as expected. However, after the second and subsequent clicks, it prints
polygon exists
-1567658064 points
Or some other seemingly random number. Anybody know what is going on here? Why is the value not staying at 0? Any help is appreciated.