George
George

Reputation: 193

C++ use of public variables from different classes

I want to access public variables from different classes in C++. I am having trouble to do it. For exemple, I have

class A{
  public:
  int x;
  int getX();
};

After that, I want to use x in a class B. There is no inheritance between class A and class B, they are just two separate classes. The problem is that, in class B I do not have an object of type A and so I cannot call the function getX. Can you tell me a way so as to use the variable x(defined in A) in class B? Thank you

Upvotes: 0

Views: 419

Answers (2)

AkaSh
AkaSh

Reputation: 526

class b
{
public:
    void member function(const a &instance)
    {
        cout<<a.x;
    }
};

Access data member of class a through member function of class b

Upvotes: 1

vikrant
vikrant

Reputation: 433

I think you need to define them as static.

class A {
   public:
     static int x;
}

in class B, you can access it..

A::x;

But there will be only single instance of x, which will be shared between all the objects of class A.

Upvotes: 1

Related Questions