static members of objects

Categories: Programming
Comments: 3 Comments
Published on: March 16, 2006

I think I am going to scream. I have an object in a lib that I made, this object has a static member that I expect (as per the C++ specs) that it should be the value I set it to last time I used it. So imagine the following class.
[code]
class a
{
private:
static int A;
public:
static void setA(int v) { A = v; };
static int getA() { return A; };
// there is more stuff but these are what is important
};
[/code]
that is the .h file, now the .cpp file has
[code]
int a::A = 0;
[/code]
Now the above code is compiled up into its own .lib file (MSVC++ 6.0) Now I have another lib that is linked to the above lib and it does something like
[code]
void f()
{
a::setA(20);
}
[/code]
now lets say I have a program that links to the second lib so lets say I call the following
[code]
void main()
{
f();
cout << a::getA() << endl; } [/code] I would expect the output to be [code] 20 [/code] but the output is [code] 0 [/code] I am trying to figure out how to have the value of a::A to stay the same across the calls to the libs.

3 Comments
  1. Rob says:

    Your program rejected my comment. Given that I couldn’t help you much, perhaps it’s no wonder! I haven’t worked with C++ in years. Sorry.

  2. If you could mail that comment to me, I could tell you what word it hit. I have a long list of rejected words since they are used alot in spam, I am guessing you used the work in-tersting, I will admit I am unsure about, since I can see a lot of people using that word

  3. Max says:

    Oh it’s funny, I’m so used to Perl and doing it the easy way that I had to think about this for a bit. You’re a programmer though Mike… what happens when software doesn’t do what you want it to do? Flood it with debugging messages and see where it’s breaking. Do some printouts or run debugging loops on each part of the code. Print value passed in and before/after variable was set. Also create a constructor that sets A to something like 2, so you know it’s not set to 0 by default and the value indeed is changed. That’s what I’d do. Code seems pretty straight forward, seems like a visibility problem – the real variable isn’t being set. I don’t deal with anything like this anymore, but I have something useful in my code that prints out debugging information if I set one global debugging flag. I rarely use it and have been writing perfect code for a while now , but sometimes when you get stuck, it’s easier to see where it’s messing up. Good luck!

Close Print