static variables in class:please help

closed account (yUq2Nwbp)
let i have a class

class
{
static int a;
public:
void f()
{
// here is code
}
};

how can i use my private static variable in member functions??..if it is possible
Last edited on
static member variables don't refer to an instanciated object, but to the whole class. To use them you have to include the class scope, I mean ClassName::a (assuming your class is named ClassName).

Remember you have to declare the same variable also outside the class. There are plenty of examples on the internet if you need them (just google c++ static member variables)

I hope It helps...
Last edited on
closed account (yUq2Nwbp)
i found in internet this example

#include <iostream>
using namespace std;

class myclass {
static int i;
public:
void setInt(int n) {
i = n;
}
int getInt() {
return i;
}
};


int myclass::i; // Definition of myclass::i. i is still private to myclass.

int main()
{
myclass object1, object2;

object1.setInt(10);

cout << "object1.i: " << object1.getInt() << '\n'; // displays 10
cout << "object2.i: " << object2.getInt() << '\n'; // also displays 10

return 0;
}

but i don't understand why must write int myclass::i; in global scope??
You have to include the class scope because when you are dealing with this kind of variable, the declaration of the static variable does not define it, so you must define it outside the class. I think to myself this is just a rule to remember.

Take in mind that this is a special variable which can even be used without declaring any myclass object.
navarromoral >> I believe you are referring to a public static variable. In his case, the default scope is private. he can only assign value by the proper get/set method which is assigned in the class. The variable here, is defined, but not assigned.

david91 >> I would think that the variable is declared static for "persistence" reasons. Once the variable holds a value, it can be pulled from all values that access that static variable - hence object1 and object2 have the same value. If you defined it locally, it would not hold value.

Last edited on
I was talking in general about static member variables. When the scope is private only function members are allowed to access this variable(and there is no need to include classname::), but I think all I have said holds true.
Topic archived. No new replies allowed.