'How to return static variable from static funtion

I have a static variable of bool type returning from static function in Class A, which is later accessed in class B like A::StaticFUn()

Now I want to pass this to another Class C, where the same static variable value should be used. Any change in static variable in A should immediately get updated in class C.

That means I should get the most updated value or real time vale of Class A when Class C use it.

MessagePolicy.h
{
public:
  static bool getDelayMessages();
private:
  static bool messagesProcess;
}

MessagePolicy.cpp
bool MessagePolicy::messagesProcess = 0;  //Global
bool MessagePolicy::getDelayMessages()
{
    return messagesProcess;
}

ClassB
bool msgst = MessagePolicy::getDelayMessages();

Class *C;
c->addvalue(MessagePolicy::getDelayMessages()) // what happens here, is it pass by value or reference

How can I pass the realtime valu to class C, Pass by reference or pointer how to do



Solution 1:[1]

Here is how you can use a reference to a bool variable in your class C:

#include <iostream>

class MessagePolicy {
public:
    static bool& getDelayMessages() { return messagesProcess; }
    static void setDelayMessages(bool b) { messagesProcess = b; }
private:
    static bool messagesProcess;
};

bool MessagePolicy::messagesProcess = false;  //Global

class C {
public:
    C(bool& b) : m_b(b) {}
    bool& m_b;
};

int main() {
    C c(MessagePolicy::getDelayMessages());
    std::cout << c.m_b << std::endl;
    MessagePolicy::setDelayMessages(true);
    std::cout << c.m_b << std::endl;
}

Please note: you can't re-assign a reference, so if you really need c->addvalue() function, you should use pointer instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vlad Feinstein