C++ Variables – Should Local Variables Be Declared in Corresponding Headers?

cheadersvariables

So for example, I create a class with two functions:

foo.h

class foo
{
public:
    foo();
    void bar();
    void ey();
    bool m_memberBool;
    bool localBool; // ??? Should I put this here?
};

foo.cpp

#include "foo.h"

foo::foo() {
    bool m_memberBool = true;
}
void foo::bar() {
    bool localBool = true;
    if (localBool && m_memberBool) {
        ey();       
    }
}
void foo::ey() {
    m_memberBool = false;
}

Should I ever include that local variable, or any local variable ever in a header? If not, should I ever document it in the header?

Best Answer

Technically, the correct answer to your question is that it's a contradiction in terms. As soon as you raise a variable into the class definition, it is no longer a local variable, it is a member variable.

But I assume you're asking whether or not there's ever a good reason to raise a local variable up into member variable status. This question comes down to the purpose of your class and that variable.

The general rule of thumb is: all variables should be declared in the narrowest possible scope. In other words, do not declare it where all of foo can use it if only foo::bar needs to use it. It's generally a bad idea for code to have access to variables it doesn't actually need, because that increases the risk that they will eventually depend or rely on those variables having certain values at certain times, which couples them to all the other code using those variables, making it harder to change one part without breaking others.

Do the other methods of foo actually need to access this bool? If not, keep it local. You can always raise it later if a good reason presents itself.