After reading StackOverflow's discussions and implementing some advices, I have these pieces of code intended just to test the behavior of static members of a class. Here is the header, which has the class declaration:
class OurClass
{
private:
static int x, y;
public:
static void setVals(int valx, int valy);
static int getValx();
static int getValy();
static void initialize();
};
And here is the cpp file, which has the definition of these members as well as the main() function:
#include <iostream>
#include "OurClass.hpp"
using namespace std;
void OurClass::initialize()
{
static int x = 0;
static int y = 0;
}
void OurClass::setVals(int valx, int valy)
{
static int x = valx;
static int y = valy;
}
int OurClass::getValx()
{
static int x;
return x;
}
int OurClass::getValy()
{
static int y;
return y;
}
int main(void)
{
OurClass::inicializa();
cout << "Provide x and y..." << endl;
OurClass::setVals(cin.get(), cin.get());
cout << "Value of x: " << OurClass::getValx() << endl;
cout << "Value of y: " << OurClass::getValy() << endl;
return 0;
}
So, assuming that a static variable exists for the class, and that static functions only access static variables, I was expecting that x and y would have the values that we read from the keyboard with the setVals() call in main(). But when printing their values in the couts, they still have the value we assigned in the initialize() function (which BTW was another suggestion I got here, that is, initialize a static variable in a method). I am also unable to refer directly to the variables by OurClass::x or y even if I make them public. Do you guys know why?
static int y;you define a function-scope local static variable. Those are different for each function and they are different from the classes static member variables. If you want to use those only, you have to remove the variable definitions and just usexandy.xand/oryasstatics. So each function is modifying a variable that is local to it, rather than the ones declared at file scope. This typically results from copying declarations into functions (e.g. a copy/paste problem) so I'm voting to close as a typographic error.static? Seriously, why?