Objects and Classes in C++: The Scope of Variables

The scope of instance and static variables is the entire class, regardless of where the variables are declared.      

Chapter 6 discussed the scope of global variables, local variables, and static local variables.

Global variables are declared outside all functions and are accessible to all functions in its scope. The scope of a global variable starts from its declaration and continues to the end of the program. Local variables are defined inside functions. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. Static local variables are permanently stored in the program so they can be used in the next call of the function.

The data fields are declared as variables and are accessible to all constructors and functions in the class. Data fields and functions can be in any order in a class. For example, all the fol­lowing declarations are the same:

This section discusses the scope rules of all the variables in the context of a class.

You can declare a variable for data field only once, but you can declare the same variable name in a function many times in different functions.

Local variables are declared and used inside a function locally. If a local variable has the same name as a data field, the local variable takes precedence, and the data field with the same name is hidden. For example, in the program in Listing 9.12, x is defined as a data field and as a local variable in the function.

Listing 9.12 HideDataField.cpp

1 #include <iostream>
using namespace std;
class Foo
5 {
int x; // Data field
8    int y; // Data field
10    Foo()
11    {
12       x =
13       y =
14    }
void p()
17    {
int x = 20; // Local variable
19        cout << “x is ” << x << endl;
20        cout <<
“y is ” << y << endl;
21    }
22 };
int main()
25 {
26     Foo foo;
27     foo.p();
return 0;
30 }

Why is the printout 20 for x and 10 for y? Here is why:

  • x is declared as a data field in the Foo class, but is also defined as a local variable in the function p() with an initial value of 20. The latter x is displayed to the console in line 19.
  • y is declared as a data field, so it is accessible inside function p().

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *