How access class variables in c++
42,296
Solution 1
class Myclass
{
public:
static int i;
};
int Myclass::i = 10;
class YourClass
{
public:
void doSomething()
{
Myclass::i = 10; //This is how you access static member variables
}
};
int main()
{
YourClass obj;
obj.doSomething();
return 0;
}
Solution 2
static
is the right keyword here:
class A {
public:
static int i; // <-- this is a class variable
};
class B {
public:
void f() { A::i = 3; } // <-- this is how you access class variables
};
They only potential problem I can think of is that
- You made the class variable
protected
orprivate
, thus rendering it inaccessible from other code. - You forgot to specify the full scope of the class variable (with
A::
in this example).
Author by
buddy
Updated on December 06, 2020Comments
-
buddy over 3 years
Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable. I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.
-
buddy over 12 yearsTHANK YOU. I would have accepted your answer too, but i had to decide.
-
HolyBlackCat over 4 yearsOP wanted to do it "without creating an object".
-
Bomel almost 2 yearsBest answer ever!