Joemoor94
Joemoor94

Reputation: 173

how do I access class attribute of an object from inside an object passed into that object?

So I've created a class that accepts another object as a reference. The problem is.. I would like to access some of the attributes from the object that is passing the object inside the objects being passed. I really just need two way communication between my objects and I'm not exactly sure of the best way to get this done.

class A {
    private:
        void someMethod();
    public:
        A();
};

class B {
    protected:
        char someAttribute;
        A& a; 
    public:
        B(A& a);
};

someMethod() {
    char newAttribute = someAttribute;
}

I would like someMethod to have access to someAttribute. I'm not sure if this is even the right way to got about this problem. I'm passing the object into another object in the main function. I'm not sure how much would change if I instanced the class directly inside the the other class.

I also tried making A a child class but it didn't work and I think this would create two separate instances of the parent class which doesn't make any sense to me.

Then I tried using friend.

class A {
    private:
        void someMethod();
    public:
        A();
};

class B {
    protected:
        char someAttribute;
        friend class A;
        A& a; 
    public:
        B(A& a);
};

someMethod() {
    char newAttribute = someAttribute;
}

I'm not sure the right way to do it but the above code doesn't work.

If someone has a much better way of implementing this code, I'm all ears.

Upvotes: 3

Views: 110

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16446

You could pass a reference (pointer):

class B;

class A {
    private:
        void someMethod();
        B *b = nullptr;
    public:
        A();
        void setRef(B &b) {this->b = &b;}
};

class B {
    friend A;
    protected:
        char someAttribute;
        A& a; 
    public:
        B(A& a) : a(a) {this->a.setRef(*this);}
};

void A::someMethod() {
    if (b)
    char newAttribute = b->someAttribute;
}

If it becomes more complex you could use a weak_ptr

Upvotes: 1

Nilesh Solanki
Nilesh Solanki

Reputation: 356

You can also do following way.If You are not bounded with other limitations. Using forward declartion of class.

   class B
    {
    protected:
        char someAttribute;
    public:
        friend class A;
    };
    
    class A
    {
    private:
         void someMethod(B b);
    public: 
    };
    
    void A::someMethod(B b)
    {
        char newAttribute = b.someAttribute;
    }

Upvotes: 0

Related Questions