NeedForSleep
NeedForSleep

Reputation: 11

Modifying a variable in class that calls function of another class

I have a problem, and I am almost certain I can find a solution by restructuring the code I have to eliminate the problem, but I was wondering if there was a way to achieve the same result with what I have right now.

Suppose we have class A:

class A
{
public:
    int thing;
    void dostuff();
    std::list<B> mList;
}

void A::doStuff()
{
    for(auto x : mList)
        x.doMoreStuff();
}

And then there is class B.

class B
{
    void doMoreStuff();
}

Is it possible in any way to make B's doMoreStuff change the 'int thing' variable of class A without passing the instance of class A to B or similar convoluted methods?

Upvotes: 0

Views: 69

Answers (3)

Shogunivar
Shogunivar

Reputation: 1222

If you only want to change the value of a certain instance you'll have to reference.

Tho something you could do is use the return value of the method in B

class A
{
    int thing;
    B b;
    void dostuff() {
        thing += b.doMoreStuff();
    };
}

class B
{
    int doMoreStuff() {
       return 1;
    };
}

Or you can make either int thing or void doMoreStuff() a static so it can be accessed from class memory instead of instance memory like so:

class A
{
    static int thing;

    void dostuff() {
        B.DoMoreStuff();
    };
}


class B
{
    static void doMoreStuff() {
       A.thing += 2;
    };
}

Upvotes: 2

Loay Ashmawy
Loay Ashmawy

Reputation: 687

Yes you can by simply passing the address of the int thing of A for example:

B.doMoreThing(&myInt);

and the definition of doMoreThing would be: doMoreThing(int * myInt) and when modifying the value of the int inside the function you should do for example *myInt+=5 the * is important to access the variable.

Upvotes: 1

inox
inox

Reputation: 26

You're not going to be able to write to thing without a reference or a pointer to it. That said, thing is private anyway, so you'd need a setter. Alternatively you could make B a friend of A, or give B a pointer to member to thing.

Upvotes: 0

Related Questions