-3

I want to access a variable of one class into another class, and set it to some value, e.g. like in code here, i wanna set the some_flag to true in the secondClassFunction(). Is it possible? If yes, how to do it?

Constraints due to system architecture:

  1. The two classes are not inheritable.
  2. The two classes are not related either.
  3. The function signatures of secondClassFunction()cannot be changed.

Here's the code snippet:-

#include <iostream>
using namespace std;

class FirstClass{
    bool some_flag;
    public:
        void setFlag(bool flag);
        bool getFlag();
};

FirstClass::FirstClass(){
    some_flag(false);
}

class SecondClass{
    public:
        void secondClassFunction();
}

SecondClass::secondClassFunction(){
    // do something here.

    // I want to access some_flag using SecondClass object.
    // how to do this?
}

int main() {
    SecondClass secObj;
    secObj.secondClassFunction();
    return 0;
}

Will wrapper classes help? If yes, how?

EDIT:-

Constraint 4. Cannot make the classes friend functions.

Constraint 5. Cannot globalize the flag variable.

Details:-

The flag is set in a function which is a member of FirstClass. I wish to reset this flag in a function which is member of the SecondClass. The two classes are not related, inheritable, and their access specifiers cannot be changed, due to constraints of the system architecture.

The flag is like a semaphore, it's used by multiple tasks, to denote the status of an activity, such as, whether the processor has received a certain command from a mobile app or not.

cappy0704
  • 557
  • 2
  • 9
  • 30

1 Answers1

0

It seems that you do not care about instance of the FirstClass. So the following approach will work for you:

void SecondClass::secondClassFunction()
{
    // Create local instance of the object to change
    FirstClass first;
    first.setFlag(true);
}

But it makes no sense at all. You need to know which object to modify. I'd suggest three options:

  • make instance of FirstClass static, global or singleton and modify it
  • make some_flag and its setter static
  • set instance of the FirstClass to context before calling SecondClass::secondClassFunction()

Third option explained:

class FirstClass; // Forward declaration
 class SecondClass
{
...
    FirstClass* firstClassInstance;
...
    void setFirstClassInstanceToModify(FirstClass* first)
    {
        firstClassInstance = first;
    }
...
};

void SecondClass::secondClassFunction()
{
    firstClassInstance->setFlag(true);
}

And call it like this

FirstClass first;
...
SecondClass second;
...
second.setFirstClassInstanceToModify(&first);
second.secondClassFunction();

But make sure to have proper and valid instance before calling secondClassFunction

Teivaz
  • 5,462
  • 4
  • 37
  • 75