6

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.

1
  • 1
    You need to be more specific. Perhaps post some example code. Commented Aug 16, 2011 at 12:04

4 Answers 4

7
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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

can i create a class variable without using static keyword?
4

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

  1. You made the class variable protected or private, thus rendering it inaccessible from other code.
  2. You forgot to specify the full scope of the class variable (with A:: in this example).

2 Comments

THANK YOU. I would have accepted your answer too, but i had to decide.
@frerichraabe can i create a class variable without using static keyword?
0

I think the Singleton Pattern would help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.

Comments

-1

yes you can bro, try this

struct car{

        string model;
        string paint;
        int price;


           };


         int main(){

          // creates an object of the class car

            car BMW;

          // assign the values
           bmw.model = "m sports";
            bmw.paint ="red";
            bmw.price = 24000;


              }

2 Comments

OP wanted to do it "without creating an object".
Best answer ever!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.