00 Pointers
00 Pointers
Unviversity
POINTERS
1. C and C++ pointers are scalar types that store addresses of other objects
(variables)--they point to other objects. Pointers are usually used in
combination with memory management operations that allocate memory when
it is needed and release that memory when it is no longer needed, e.g. string
objects that may grow or shrink in length while the program is executing.
2. Because C and C++ have the capability to access specific memory locations
via pointers, it is an appropriate language for writing operating systems.
type-name *identifier;
a) After the following declaration, the pointer named intPtr may store the
address of any int object. Currently, the pointer intPtr has not been
assigned a value (address).
1
OOP Course Al-Balqa Applied
Unviversity
POINTERS (CONTINUED)
123
anInt
p ?
6. When the pointer is assigned an address, the arrow points to the object stored
at the address. Pointers may be assigned values through the & operator,
which is called the address of operator. The address of operator returns the
address of its operand.
& object-name
a) The following statement stores the address of anInt into the pointer p
(the expression &anInt is read as "address of anInt"):
123
anInt
address
p of anInt
2
OOP Course Al-Balqa Applied
Unviversity
POINTERS (CONTINUED)
7. The value of the object pointed to by a pointer can also be altered indirectly.
The contents of anInt can be changed without even using anInt's name.
Indirect addressing with the dereference, or indirection, operator *, allows
inspection or change of the contents of memory pointed to by the pointer.
-654
anInt
address
p of anInt
3
OOP Course Al-Balqa Applied
Unviversity
POINTERS (CONTINUED)
int main()
{
double *p1, *p2, *temp; // Three *s means 3 pointer objects
double n1, n2;
Output is:
*p1 and *p2 before switch
99.9 88.8
*p1 and *p2 after switch
88.8 99.9
4
OOP Course Al-Balqa Applied
Unviversity
POINTER ARITHMETIC
2. When adding 1 to a variable of pointer type, you are actually changing the
address contained in the pointer to point to the next variable in memory of
that particular type.
a) The expression
k = floatptr1 - floatptr2;
defines k such that
floatptr2 + k == floatptr1
floatptr1 + floatptr2
5
OOP Course Al-Balqa Applied
Unviversity
/* address3.cpp
*
* Synopsis - Uses pointers to print the addresses of a char
* variable and an int variable and the address of
* the next available memory location for each
* data type.
*
* Objective - Illustrates what is meant by a pointer-to-int
* being a separate data type. Demonstrates syntax
* of declaring a pointer-to-char variable,
* initialization of pointer variables, and
* the result of adding 1 to pointer variables
* of different types.
*/
// Include Files
#include <iostream.h>
int_ptr = &intvar;
cout << "The address of charvar is " << char_ptr << endl;
cout << "The next character could be stored at "
<< (char_ptr + 1) << endl; // references the next potential
// address of a char
cout << "The address of intvar is " << int_ptr << endl;
cout << "The next integer could be stored at "
<< (int_ptr + 1) << endl; // references the next potential
// address of an int
}
6
OOP Course Al-Balqa Applied
Unviversity
7
OOP Course Al-Balqa Applied
Unviversity
/* param.cpp
*
* Synopsis - Displays the values of variables and parameters
* before, during, and after a function call.
*
* Objective - Illustrates passing pointer parameters.
*/
// Include Files
#include <iostream.h>
// Function Declarations
void changit( int, int * );
x = 1;
y = 3;
int_ptr = &y; // the value of y will eventually be changed by changit()
cout << "In main after the call to changit,"; // x will be unchanged
cout << " x = " << x << ", y = " // y will be changed
<< y << ", *int_ptr = " << *int_ptr << endl;
}
8
OOP Course Al-Balqa Applied
Unviversity
cout << "In changit, x = " << x // print will differ from
<< ", *int_ptr = " << *int_ptr << endl; // print in main()
}
Output is:
9
OOP Course Al-Balqa Applied
Unviversity
1. The new and delete operators are used to perform dynamic memory
allocation (for any built-in or user-defined type).
2. To allocate space from the heap to store an integer, you would write:
int *intPtr;
intPtr = new int;
4. To free the space for an object created by new in C++, you must use the
delete operator as follows:
delete intPtr;
a) delete eliminates a dynamic variable and returns the memory that the
dynamic variable occupied to the heap. The memory can then be
reused to create new dynamic variables.
b) delete returns type void.
c) delete invokes the class destructor if necessary.
5. C++ allows you to provide an initializer for a newly created object. In the
following, the newly created float object is initialized to 3.14159:
10
OOP Course Al-Balqa Applied
Unviversity
TYPEDEFS
2. Names for structure types are often defined with typedef to create shorter or
more readable type names.
a) The following example defines the new type name CardPtr as a
synonym for type Card *:
struct Card {
int face;
int suit;
};
b) After the typedef, the new identifier can be used to declare variables of
that type.
CardPtr ptr_to_card;
3. Creating a new name with typedef does not create a new data type.
a) typedef simply creates a new type name which may then be used in the
program as an alias for an existing type name.
11
OOP Course Al-Balqa Applied
Unviversity
TYPEDEFS (CONTINUED)
12
OOP Course Al-Balqa Applied
Unviversity
STORAGE CLASSES
13
OOP Course Al-Balqa Applied
Unviversity
1. The auto and register keywords are used to declare variables of the
automatic storage class. Such variables are created when the block in which
they are declared is entered, they exist while the block is active, and they are
destroyed when the block is exited.
2. Only variables can be of automatic storage class, i.e. they exist only in the
body of the function in which the declaration appears.
a) Automatic storage is a means of conserving memory because automatic
storage class variables are created when the block in which they are
declared is entered and are destroyed when the block is exited.
b) A function's local variables and parameters normally are of automatic
storage class so the auto keyword is rarely used.
c) The storage class specifier auto explicitly declares variables of
automatic storage class.
i) In the following declaration, float variables x and y are local
variables of automatic storage class.
auto float x, y;
d) The register keyword can be used only with local variables and
function parameters.
14
OOP Course Al-Balqa Applied
Unviversity
15
OOP Course Al-Balqa Applied
Unviversity
1. The keywords extern and static are used to declare identifiers for variables
and functions of the static storage class.
a) Such variables exist from the point at which the program begins
execution.
b) For variables, storage is allocated and initialized once when the
program begins execution.
c) For functions, the name of the function exists when the program begins
execution.
d) Even though the variables and the function names exist from the start
of the program execution, this does not mean that these identifiers can
be used throughout the program.
i) Storage class and scope have a controlling influence.
3. Global variables:
a) Are created by placing variable declarations outside any function
definition.
b) Retain their values throughout the execution of the program.
c) When defined, they are known from their point of declaration to the
end of the source file.
d) Have external linkage; this means that they can also be referenced in
other source code files as well as in functions below their point of
definition.
i) Code in other source code files can declare (but not define) this
same variable and give it the storage class extern.
16
OOP Course Al-Balqa Applied
Unviversity
f1()
{
...
}
iii) The keyword extern is used with declarations, but not with
definitions of variables.
a) It indicates that the variable is defined elsewhere.
b) References should be resolved during the link phase of
compilation.
4. Global variables and functions can be referenced by any function that follows
their declarations for definitions in the file.
17
OOP Course Al-Balqa Applied
Unviversity
6. Local variables declared with the keyword static are known only in the
function in which they are defined, but unlike automatic variables, static local
variables retain their value when the function is exited. The next time the
function is called, the static local variable contains the value it had when the
function last exited.
a) All numeric variables of the static storage class are initialized to zero if
they are not explicitly initialized by the programmer.
b) The following statement declares local variable count to be static and
to be initialized to 1.
18
OOP Course Al-Balqa Applied
Unviversity
// A scoping example
#include <iostream.h>
main()
{
int x = 5; // local variable to main
cout << "local x in outer scope of main is " << x << endl;
cout << "local x in inner scope of main is " << x << endl;
} // end new scope
cout << "local x in outer scope of main is " << x << endl;
return 0;
}
19
OOP Course Al-Balqa Applied
Unviversity
void a(void)
{
int x = 25; // initialized each time a is called
void b(void)
{
static int x = 50; // Static initialization only
// first time b is called.
cout << endl << "local static x is " << x
<< " on entering b" << endl;
++x;
cout << "local static x is " << x
<< " on exiting b" << endl;
}
void c(void)
{
cout << endl << "global x is " << x
<< " on entering c" << endl;
x *= 10;
cout << "global x is " << x << " on exiting c" << endl;
}
20
OOP Course Al-Balqa Applied
Unviversity
Output is:
global x is 1 on entering c
global x is 10 on exiting c
local x in a is 25 on entering a
local x in a is 26 before exiting a
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5
21
OOP Course Al-Balqa Applied
Unviversity
22
OOP Course Al-Balqa Applied
Unviversity
// ARRAY1.H
// Simple class Array (for integers)
#ifndef ARRAY1_H
#define ARRAY1_H
#include <iostream.h>
class Array {
friend ostream &operator<<(ostream &, const Array &);
friend istream &operator>>(istream &, Array &);
public:
Array(int = 10); // default constructor
Array(const Array &); // copy constructor
~Array(); // destructor
int getSize() const; // return size
Array &operator=(const Array &); // assign arrays
int operator==(const Array &) const; // compare equal
int operator!=(const Array &) const; // compare !equal
int &operator[](int); // subscript operator
private:
int *ptr; // pointer to first element of array
int size; // size of the array
};
#endif
23
OOP Course Al-Balqa Applied
Unviversity
// ARRAY1.CPP
// Member function definitions for class Array
#include <iostream.h>
#include <stdlib.h>
#include <assert.h>
#include "array1.h"
24
OOP Course Al-Balqa Applied
Unviversity
25
OOP Course Al-Balqa Applied
Unviversity
26
OOP Course Al-Balqa Applied
Unviversity
if ((i + 1) % 10 == 0)
output << endl;
}
if (i % 10 != 0)
output << endl;
27
OOP Course Al-Balqa Applied
Unviversity
// FIG8_4.CPP
// Driver for simple class Array
#include <iostream.h>
#include "array1.h"
main()
{
// create two arrays
Array integers1(7), integers2;
28
OOP Course Al-Balqa Applied
Unviversity
29
OOP Course Al-Balqa Applied
Unviversity
return 0;
}
Output is:
Input 17 integers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
After input, the arrays contain:
integers1: 1 2 3 4 5 6 7
integers2: 8 9 10 11 12 13 14 15 16 17
30
OOP Course Al-Balqa Applied
Unviversity
integers1[5] is 13
Assigning 1000 to integers1[5]
integers1: 8 9 10 11 12 1000 14 15 16 17
31
OOP Course Al-Balqa Applied
Unviversity
COPY CONSTRUCTOR
3. Copying must be done carefully to avoid the pitfall of leaving both objects
pointing to the same dynamically allocated storage, exactly the problem that
would occur with default memberwise copy.
a) If a copy constructor copies a pointer in the source object to the target
object's pointer, then both objects would point to the same dynamically
allocated storage.
b) The first destructor to execute would then delete the dynamically
allocated storage and the other object's pointer would then be
undefined, a situation likely to cause a serious runtime error.
32
OOP Course Al-Balqa Applied
Unviversity
ASSIGNMENT OPERATOR
integers1 = integers2;
integers1.operator=(integers2)
33
OOP Course Al-Balqa Applied
Unviversity
BIBLIOGRAPHY
Cantu, Marco and Steve Tendon, Borland C++ 4.0 Object-Oriented Programming,
New York: Random House, 1994.
Deitel, H.M. and P.J. Deitel, C++ How to Program, Second Edition, Eaglewood
Cliffs, New Jersey: Prentice Hall, 1998.
Gorlen, Keith E., Sanford M. Orlow, and Perry S. Plexico, Data Abstraction and
Object-Oriented Programming in C++, New York: John Wiley & Sons, 1991.
Horstmann, Cay S., Mastering Object-Oriented Design in C++, New York, NY:
John Wiley & Sons, Inc., 1995.
Savitch, Walter, Problem Solving with C++, Second Edition, Menlo Park, Ca.:
Addison-Wesley Publishing Company, Inc., 1999.
Swan, Tom, Mastering Borland C++ 4.5, Second Edition, Indianapolis, Indiana:
SAMS, 1995.
34