Revised: January 29, 2007
By Richard G. Baldwin
File: Pf00140.htm
Practice Text
This lesson was written specifically for the benefit of my students in COSC 1315, Fundamentals of Programming. The lesson was written under the assumption that those students have no prior programming knowledge when they enroll in the course.
Another browser window
I recommend that you open another copy of this document in a separate browser window so that you can view the code and the discussion of that code at the same time.
Four kinds of variables
This lesson deals with five different kinds of variables plus constants:
Scope
The scope of a variable determines the set of program instructions in which the variable is accessible.
With the exception of pointer variables, the scope generally decreases going down the above list.
Declaring a variable
A variable is a named pigeon hole in memory where data is stored.
All variables must be declared before they can be used.
The declaration of a variable consists of two parts:
Sample variable declaration
A sample variable declaration is shown below:
int aVariable;
In this example, the name of the type is int, and the name of the variable is aVariable.
Initializing a variable
In some cases, the initial contents of a variable can be established when the variable is declared, as in the following statement:
int aVariable = 55;
C++ allows global variables. C# and Java do not allow global variables.
Generally speaking, it is probably a bad idea to use global variables in your programs.
The C++ program in Listing 1 illustrates the scope of a global variable.
/*File: Variables01.cpp This C++ program illustrates global variables. A global variable is declared and initialized to a value of 0. This variable is accessed from three different places in the program where its current value is displayed. Then the value is changed and the value is displayed again. The program displays the following on the screen: In global main function. globalVariable = 0 globalVariable = 1 In classMain function. globalVariable = 1 globalVariable = 2 In doSomething function. globalVariable = 2 globalVariable = 3 Press any key to continue ************************************************/ #include <iostream> using namespace std; int globalVariable = 0;//Initialize to 0 class Variables01{ public: static void classMain(){ //Display, modify and then display the value // of the global variable again. cout << "In classMain function.\n"; cout << "globalVariable = " << globalVariable << endl; globalVariable = globalVariable + 1; cout << "globalVariable = " << globalVariable << endl; //Instantiate an object in dynamic memory // and save its reference in a pointer // variable. Variables01* ptrToObject = new Variables01(); //Invoke an instance function on the object. ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Variables01 class void doSomething(){ //Display, modify and then display the value // of the global variable again. cout << "In doSomething function.\n"; cout << "globalVariable = " << globalVariable << endl; globalVariable = globalVariable + 1; cout << "globalVariable = " << globalVariable << endl; }//end doSomething function };//End Variables01 class //---------------------------------------------// int main(){ //Display, modify and then display the value // of the global variable again. cout << "In global main function.\n"; cout << "globalVariable = " << globalVariable << endl; globalVariable = globalVariable + 1; cout << "globalVariable = " << globalVariable << endl; Variables01::classMain(); return 0; }//end main Listing 1 |
What is a global variable?
A global variable is a variable that is declared:
The variable named globalVariable
A global variable named globalVariable is declared and initialized to a value of 0 in Listing 1.
This variable is accessed from three different locations in the program. The three locations are highlighted in boldface.
The current value is displayed each time the variable is accessed from a different location. Then the value is incremented by one and the value is displayed again.
The output
The output produced by the program is shown below:
In global main function. globalVariable = 0 globalVariable = 1 In classMain function. globalVariable = 1 globalVariable = 2 In doSomething function. globalVariable = 2 globalVariable = 3 Press any key to continue
Scope of a global variable.
A global variable is accessible by any code in any function (including global functions) in the program that knows the name of the variable.
The C++ program shown in Listing 2 illustrates the use of a static class variable.
/*File: Variables02.cpp This C++ program illustrates the use of a static class variable. The program defines a class named Variables02, which declares a public static variable named aStaticVariable. The code in the main method accesses the class variable three times in succession with no requirement to instantiate an object of the class. The first access displays the initial value of the variable. The second access modifies the value of the variable. The third access displays the modified value. Note that in C++, static class variables cannot be initialized inside the class. A global initializer is used to initialize the class variable in this program. You are required to initialize static class variables or they will not be in scope and will not be accessible. The required initialization syntax is: type class_name::static_variable = value Note that you must include the type of the static variable when you initialize it. The program displays the following output: 0 6 Press any key to continue A good explanation of the use of static class members in C++ is available at: http://www.cprogramming.com/tutorial/ statickeyword.html ************************************************/ #include <iostream> using namespace std; class Variables02{ public: //Declare a public static class variable. See // initialization below. static int aStaticVariable; };//End Variables02 class //---------------------------------------------// int main(){ //Access the static class variable without a // requirement to instantiate an object of // the Variables02 class. cout << Variables02::aStaticVariable << endl; Variables02::aStaticVariable = 6; cout << Variables02::aStaticVariable << endl; return 0; }//end main //Must initialize the static variable outside // the class. It is not in scope and cannot be // accessed until it is initialized. You must // specify the type of the variable when you // initialize it. int Variables02::aStaticVariable = 0; Listing 2 |
Characteristics of a class variable
Such variables are referred to as static variables and are also referred to as class variables.
A class variable is declared inside a class but not inside a function, and is declared to be static.
Only one copy of a static variable exists no matter how many objects (if any) are instantiated from the class. That copy is shared among all of the objects that may be instantiated from that class.
A public static variable can be accessed without a requirement for an object instantiated from the class.
Static class variables should be used very sparingly if at all.
A static variable named aStaticVariable
The program in Listing 2:
Access without an object of the class
The code in the main method accesses the class variable three times in succession with no requirement to instantiate an object of the class.
The scope resolution operator (::) is used in conjunction with the class name to access a static variable in the absence of an object.
The first access displays the initial value of the variable.
The second access modifies the value of the variable.
The third access displays the modified value.
The output
The program displays the following output:
0 6
Initialization of static variables
In C++, you must initialize static variables or they will not be in scope and will not be accessible.
The required initialization syntax is:
type class_name::static_variable = value
Note that you must include the type of the static variable when you initialize it.
In C++, static variables cannot be initialized inside the class.
A global initializer is used to initialize the class variable in this program using the following global statement:
int Variables02::aStaticVariable = 0;
Scope of a static (class) variable
Once declared and globally initialized, a public or private static variable is accessible by all of the static and non-static functions defined in the same class.
A public static variable is accessible by any code in any function (including global functions) in the program that knows the name of the variable and the name of the class in which it is declared.
An instance variable is a variable that is declared inside a class, outside of a function, and is not declared to be static.
The program shown in Listing 3 illustrates instance variables.
/*File: Variables03.cpp This C++ program illustrates instance variables. This program instantiates two objects of type Variables03 in dynamic memory and stores pointers to the two objects in pointer variables named ptrToObj01 and ptrToObj02. The class named Variables03 has a public instance variable named instanceVariable. The program uses the two pointer variables to store values of 3 and 10 in the instance variable belonging to each of the two objects respectively. Then the program invokes an instance function named displayInstanceVariable on each of the two objects to display the contents of the instance variable encapsulated in each of the two objects. The program displays the following output on the screen: In displayInstanceVariable function 3 In displayInstanceVariable function 10 ************************************************/ #include <iostream> using namespace std; class Variables03{ public: //The following is an instance variable. int instanceVariable; static void classMain(){ //Instantiate two objects in dynamic memory // and save their references in two pointer // variables. Variables03* ptrToObj01 = new Variables03(); Variables03* ptrToObj02 = new Variables03(); //Store different numeric values in the // instance variables belonging to each of // the two objects. ptrToObj01 -> instanceVariable = 3; ptrToObj02 -> instanceVariable = 10; //Invoke the same instance function on each // of the two objects to display the values // contained in the instance variable in // each of the two objects. ptrToObj01 -> displayInstanceVariable(); ptrToObj02 -> displayInstanceVariable(); }//End classMain function //-------------------------------------------// //An instance function of the Variables03 class void displayInstanceVariable(){ cout << "In displayInstanceVariable function\n"; cout << instanceVariable << endl; }//end displayInstanceVariable function };//End Variables03 class //---------------------------------------------// int main(){ Variables03::classMain(); return 0; }//end main Listing 3 |
Every object has a separate copy
An object is an instance of a class.
Every object has its own copy of every instance variable that is declared in the class from which the object is instantiated.
Therefore, each instance variable is the property of one instance (object) of the class. (Hence the name instance variable.)
Two objects of the same class named Variables03
This program instantiates two objects of type Variables03 in dynamic memory.
The addresses of the two objects are stored pointer variables named ptrToObj01 and ptrToObj02.
The class named Variables03 declares a public instance variable named instanceVariable.
Store different values in the instance variables of the two objects
The program uses the two pointer variables to store values of 3 and 10 in the instance variable belonging to each of the two objects respectively.
Display contents of each instance variable
Then the program invokes an instance function named displayInstanceVariable on each of the two objects.
This function displays the contents of the instance variable encapsulated in the object on which it is invoked.
Output
The program displays the following output on the screen:
In displayInstanceVariable function 3 In displayInstanceVariable function 10
Scope of an instance variable
The scope of an instance variable (public or private) includes all of the code in all of the instance functions (non-static functions) that are defined in the same class.
Static functions do not have direct access to instance variables. Static functions only have access to other static members of the class (variables and functions).
When objects are instantiated in dynamic memory, public instance variables are accessible to any code anywhere in the program that has access to a pointer variable containing the address of the object in dynamic memory.
A local variable is a variable that is declared within a block of code within any function.
The C++ program shown in Listing 4 illustrates local variables.
The scope of the local variables
The program comments explain the scope of each of the local variables.
Additional information regarding the scope of a local variable follows the program listing.
Program output
The program displays the following output on the screen:
6
/*File: Variables04.cpp This C++ program illustrates local variables. The program comments explain the scope of each of the local variables. The program displays the following output on the screen: 6 ************************************************/ #include <iostream> using namespace std; class Variables04{ public: static void classMain(){ //Instantiate an object in dynamic memory // and save its reference in a local pointer // variable. Note that this variable is // local to the classMain function. Its // scope extends from the point where it is // declared to the end of the function. It // cannot be accessed from any location // outside its scope. Variables04* ptrToObject = new Variables04(); //Use the local pointer variable to invoke an // instance function on the object. ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Variables04 class void doSomething(){ //The following statement will not compile // because the statement is not within the // scope of the variable named localVariable. //cout << localVariable << endl; //The following variable is local to the // method named doSomething. Its scope // extends from the point where it is // declared to the end of the function. int localVariable = 6; cout << localVariable << endl; }//end doSomething function };//End Variables04 class //---------------------------------------------// int main(){ Variables04::classMain(); return 0; }//end main Listing 4 |
Scope of a local variable in general
The scope of a local variable extends from the point in the function where it is declared until the end of the block in which it is declared.
In the functions in Listing 4, that block consists of the entire body of the function. Thus, the scope extends from the point at which the variable is declared to the end of the function.
However, in the case where a variable is declared within a block that is nested within another block, the scope of the variable ends at the end of the nested block in which it is declared.
C++ pointer variables per se do not constitute a fundamental programming concept.
However, indirection, of which C++ pointer variables are one form, is a fundamental programming concept. Therefore, I have included pointer variables here.
Sample program illustrates use of pointer variables
A pointer variable is a variable that contains the address in memory of the thing that it points to.
The C++ program shown in Listing 5 illustrates the use of pointer variables.
/*File: Variables05.cpp This C++ program illustrates the use of pointer variables. Two pointer variables are declared and used in this program. One points to an object that is instantiated in dynamic memory. The other points to a local variable in a function. Comments in the code explain how each is used to access the object or the variable that it points to. The address stored in each of the pointer variables is displayed along with the contents of the local variable pointed to by one of the pointer variables. The program displays the following output on the screen. Note that the addresses may be different each time that the program is run. Object's address = 00481E10 Local variable's contents = 0 Local variable's address = 0012FEC8 Local variable's contents = 6 Local variable's contents = 6 ************************************************/ #include <iostream> using namespace std; class Variables05{ public: static void classMain(){ //Instantiate an object in dynamic memory // and save its address in a pointer // variable. Variables05* ptrToObject = new Variables05(); //Display the address stored in the pointer // variable. cout << "Object's address = " << ptrToObject << endl; //The -> operator is used with a pointer // variable to dereference (access) a member // of an object pointed to by the pointer // variable. //Invoke an instance function on the object. ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Variables05 class void doSomething(){ //Declare a local variable and initialize its // value. int var = 0; //Display the contents of the local variable. cout << "Local variable's contents = " << var << endl; //Declare a pointer variable and store the // address of the local variable in it. int* ptrToVar = &var; //The * operator is used with a pointer // variable to dereference (access) a variable // pointed to by the pointer variable. //Use the pointer variable to access the // local variable pointed to by the pointer // variable and store a new value in the // local variable. *ptrToVar = 6; //Display the address stored in the pointer // variable. cout << "Local variable's address = " << ptrToVar << endl; //Use the pointer variable to dereference // (access) and to display the contents of // the local variable pointed to by the // pointer variable. cout << "Local variable's contents = " << *ptrToVar << endl; //Display the contents of the local variable // directly. cout << "Local variable's contents = " << var << endl; }//end doSomething function };//End Variables05 class //---------------------------------------------// int main(){ Variables05::classMain(); return 0; }//end main Listing 5 |
Two different pointer variables
Two pointer variables are declared and used in this program.
Explanation
Comments in the code explain how each pointer variable is used to access the object or the variable to which it points.
Information that is displayed
The address stored in each of the pointer variables is displayed.
Also, the contents of the local variable pointed to by one of the pointer variables is displayed.
That pointer variable is used to change the contents of the local variable to which it points.
Then the pointer variable is used to display the new contents.
Then the new contents of the local variable are displayed without the use of the pointer variable.
Program output
The program displays the following output on the screen. (Note that the addresses may be different each time that the program is run.)
Object's address = 00481E10 Local variable's contents = 0 Local variable's address = 0012FEC8 Local variable's contents = 6 Local variable's contents = 6
The C++ program shown in Listing 6 illustrates constants.
The program shows that an attempt to modify the value of a const variable after it is initialized results in a compiler error.
The program displays the following output on the screen when the offending statement is disabled by turning it into a comment:
3.14159
/*File: Variables06.cpp This C++ program illustrates constants. The program shows that an attempt to modify the value of a const variable after it is initialized results in a compiler error. The program displays the following output on the screen when the offending statement is disabled by turning it into a comment: 3.14159 ************************************************/ #include <iostream> using namespace std; class Variables06{ public: static void classMain(){ //Instantiate an object in dynamic memory // and save its reference in a pointer // variable. Variables06* ptrToObject = new Variables06(); //Invoke an instance function on the object. ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Variables06 class void doSomething(){ //Declare and initialize a constant. const double pi = 3.14159; //The following attempt to change the value // of a constant results in a compiler error. //pi = 16.5; cout << pi << endl; }//end doSomething function };//End Variables06 class //---------------------------------------------// int main(){ Variables06::classMain(); return 0; }//end main Listing 6 |
Copyright 2005, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-