/*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