Search code examples
c++private-members

C++ variable scope


// declare a class with private variable “int * _a”

// declare a function of this class,  foo()

Void foo() {

int * _a; // 1. Does this re-declaration then make _a equal to an unknown value?
          // 2. Does a go out of scope after foo() returns?

}

Solution

    1. Does this re-declaration then make _a equal to an unknown value?

    No. This isn't a "re-declaration." It is a declaration of a local variable named _a. It is uninitialized.

    It has no relation whatsoever to the class member variable _a. After the declaration of the local _a, you cannot access the member variable _a anymore using _a (because _a refers to the local variable!), but you can refer to it using this->_a.

    1. Does a go out of scope after foo() returns?

    Yes. Local variables go out of scope when the scope in which they are declared ends (that's what "going out of scope" comes from).