user3166884
user3166884

Reputation: 11

Using a Variable of an Instance within the Method of another Class in C++

I was wondering how I would go about using a variable of a specific instance of a class within a function of another class.

To provide an example of what I'm trying to do, say I've 3 classes a,b and c. Class c inherits from class b, and a single instance of b and c are called within a method in class a and b respectively. How would I go about using the variable of int pos (see below) within a specific instance of class a in class c?

class a
{
    private:
    void B(); //Calls an instance of class c
    int pos; //Variable that I want to use in c
};

class b : public c
{
    private:
    void C(); //Calls an instance of class b
};

class c
{
    private:
    void calculate(int _pos); //Method which requires the value of pos from class a 
};

Help would be greatly appreciated, thank you!

Upvotes: 0

Views: 49

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Your code sample doesn't make much sense for me, and you aren't really clear what you want to achieve.

"How would I go about using the variable of int pos (see below) within a specific instance of class a in class c?"

Fact is you can't access any private class member variables from other classes.

Since class c and class b aren't declared as friend for class a, these cannot access the pos member from a::pos directly. You have to pass them a reference to class a; at some point, and provide public (read access) to pos with a getter function :

class a {
    int pos; //Variable that I want to use in c
public:
    int getPos() const { return pos; } // <<< let other classes read this 
                                       //     property
};

And use it from an instance of class c() like e.g. (constructor):

c::c(const a& a_) { // <<< pass a reference to a 
   calculate(a_.getPos());
}

Upvotes: 1

ChronoTrigger
ChronoTrigger

Reputation: 8607

I'm not sure if I understand your problem, but if you want to access a member of a class instance from a non-friend non-base class, that member must be exposed of there must be some function that access it. For example:

class a
{
public:
  int getPos() const { return pos; }
private:
  void B(); //Calls an instance of class c
  int pos; //Variable that I want to use in c
};

Upvotes: 0

Related Questions