Search code examples
c++private-memberspublic-method

Make a list of private variables changeable through a public function in C++


I have about 20 private bools within a class in C++. I would like for these to be publicly accessible using a (public) function.

Is it possible to pass the name of a (private) variable as an argument to such a function? For example,

void setTrue(std::string varName)
{
    someFunctionToConvertStringToVariable = true;
}

Alternatively, I think that

void setTrue(std::string varName)
{
    if (varName == "boolA")
    {
        boolA = true;
    }
    else if (varName == "boolB")
    {
        boolB = true;
    }
}

would work, and could use a switch(varName) to reduce the number of LOC needed.

Another option would presumably be to just make all of the booleans public, and then access them using myClass.boolA = true; from the calling program - I'm not sure this is the best idea, but it's certainly simpler, and so that's an argument in its favour.

Is there a generally accepted/best way to do this type of thing? Have I just set up the problem badly and is there a much smarter way to go about this? Perhaps an enum of varnames would allow passed variables to be checked, but I don't think that would necessarily make it easier to set the boolean.


Solution

  • You can use a std::map<std::string, bool> to store the bool values. Then,

    void setTrue(std::string varName)
    {
        // Add some checks to make sure that varName is valid.
    
        varNames[varName] = true;
    }