Question

I want to change a variable member of class B, in a method member of class A. Example:

A.h:
class A
{
    //several other things
    void flagchange();
}
A.cpp:
void A::flagchange()
{
    if (human) Bobj.flag=1;
}

I know that I need an object of class B, to change a variable member of B, but objects of B are not reachable in A. Is it possible by a pointer??

Was it helpful?

Solution

but objects of B are not reachable in A

If objects of class B are not reachable by class A there's no way you can modify them. Once you refactored your design, you should pass it as an argument to the function:

class A {
    //several other things
    void flagchange(B& obj) {
        if (human)
            obj.flag = 1;
    }
};

I want to be able to toggle the flag from a method of class A for every object of B

You should declare your flag public variable as static in B:

class B {
public:
    static int flag;
};

int B::flag = 0;

And then, from inside A:

class A {
    //several other things
    void flagchange() {
        if (human)
            B::flag = 1;
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top