Search code examples
c++methodsbooleannamingnames

Can a variable and a method have the same name in C++?


class Controller {

 bool isBackendActive();
 void anotherMethodDoingSomething();

}

Can I declare a boolean variable with the same name as a method so that I can use it like this:

void Controller::anotherMethodDoingSomething() {
    bool isBackendActive = isBackendActive();
    if (aBoolean && isBackendActive) {
     ...
     LOG("bla" + isBackendActive)
    }
    else if (!isBackendActive) {
     ...
    }
    else 
     ...
    }
    

Thank you a lot for your input in advance.


Solution

  • Without discussing merits (or lack thereof), yes, you can disambiguate a member from a local variable rather easily.

    bool const isBackendActive = this->isBackendActive();
    

    or

    bool const isBackendActive = Controller::isBackendActive();
    

    Will work (and might as well be const correct).