Sie sind auf Seite 1von 30

COMP6175 Object Oriented

Programming
Topic 6 Reference, Pointer, and Passing Parameter
OUTLINE MATERIALS
Topic 6 Reference, Pointer, and Passing Parameter

Reference
Pointer
Dangling Pointer
Dynamic Memory Allocation
Pointer this
Passing Parameters
Passing by Value
Passing by Address
Passing by Reference
Passing by Const Reference
Topic 6 Reference, Pointer, and
Passing Parameter
REFERENCE
A reference is an alias or synonym for another variables.
Areference(orconstant reference)variableserves as an
alternative name for an object.
References areanadditionalname toanexistingmemory location
It is declared by using the address operator & appended to the
references type
A reference must be initialized when it is declared.
Contains the address of a variable (like a pointer) but no need to
perform any dereferencing (unlike a pointer)

Ex : int &count;
Means : count is a reference to an int.
REFERENCE (2)
Areferencevariable isdifferentfromapointer
A pointer needNOTbe initialized while defining, but a
reference variable should always refer to some other object
Apointercan be assigned a new value to point at a different
object, but areference variablealways refers to the same
object.
Assigning a reference variable with a new value actually
changes the value of the referred object.
Referenceandconstant referencevariables are commonly
used for parameter passing to a function
They can also be used as local variables or as class data
members
REFERENCE EXAMPLE
# include< iostream >
using nam espace std;
int m ain() {
int n = 33;
int& r = n;// r is a reference for n
cout < < "n = " < < n < < ", r = " < < r < < endl;
n--;
cout < < "n = " < < n < < ", r = " < < r < < endl;
r *= 2;
cout < < "n = " < < n < < ", r = " < < r < < endl;
cin.get();
return 0;
}
CONSTANT REFERENCE
Aconstant reference variablevrefers to an object whose
value cannot be changed throughv.

int m=8;
const int&v=m;
m =16; //valid
v =20; //compilation error
REFERENCING IS THE OPPOSITE OF
DEREFERENCING

p reference n
r dereference p
so r is alias for n
they are different name for the same value.
int m ain() {
int n = 33;
int* p = & n;// p points to n
int& r = *p;// r is a reference for n
cout < < r = < < r < < endl;
}
POINTER
The variable p is called a pointer because its value points to the
location of another value.
The value of a pointer is an address
It is declared by using the operator * appended to the pointers
type
A pointer may not be initialized (refers to NULL) when it is declared.
The operator * is called dereferencing operator
int m ain() {
int n = 33;
int *p = & n;
cout < < *p = < < *p < < endl;
}
THREE TYPES OF MEMORY
In C/C++ programs, three types of memory
are used :
Static memory for global and static variables live
Heap memory is dynamically allocated at
execution time and "managed" memory
accessed using pointers (unnamed variable)
Stack memory for automatic variables and
function parameters
THREE TYPES OF PROGRAM DATA
STATIC DATA: Allocated at compiler time
DYNAMIC DATA: explicitly allocated and de-
allocated during program execution by C++
instructions written by programmer using operators
new and delete
AUTOMATIC DATA: automatically created at
function entry, resides in activation frame of the
function, and is destroyed when returning from
function
DYNAMIC MEMORY ALLOCATION
In C++ dynamic memory allocation is accomplished
using the new and delete operators
new is used to allocate memory during execution
time
returns a pointer to the address where the object is to be
stored
always returns a pointer to the type that follows the new
delete is used to de-allocate memory
SYNTAX FOR NEW AND DELETE
new dataType;
new dataType [intExpression];

delete pointer;
delete [] pointer;

New/delete is preferred to malloc()/free() because it can initialize


the memory and it invokes the constructor for new objects.
New/delete also point to the correct memory type.
Note on mixing source code containing new/delete and
malloc()/free(). This is not a problem with the GNU C++
compiler but this is not guaranteed for all C++ compilers.
DANGLING POINTER
A pointer that does not point to anything: uninitialized
and de-allocated pointer
Example uninitialized pointer
int *p; // p is a pointer to integer
*p = 7491; // error, no storage has been allocated for *p

SOLUTION
1. Initialize pointers when they are declared
int x = 7491; // allocates named memory
int* p = &x;
cout << *p;
DANGLING POINTER (2)
2. allocate memory for the pointer explicitly
int* p;
p = new int;
*p = 7491;

3. combine the first two of statements


int * p = new int;

4. another way
int* p = new int (7491); // allocates unnamed memory
DANGLING POINTER (3)
Example de-allocated pointer
int* p = new int (7491);
delete p;
*p = 7491; // ERROR
Note: a pointer to constant cannot be deleted
const int* p = new int;
delete p; //ERROR

Note that if the pointer is re-assigned a new value


before being freed, it will lead to a dangling pointer and
memory leak.
POINTER this
Within a member function, the this keyword is a
pointer to the current object, i.e. the object through
which the function was called
C++ passes a hidden this pointer whenever a
member function is called
Within a member function definition, there is an
implicit use of this pointer for references to data
members
POINTER this (2)
The this pointer holds the memory address of the
current object that is using the function
The this pointer is automatically supplied when you
call a non-static member function of a class
The this pointer is a constant pointer
PASSING PARAMETERS IN FUNCTION
Passing Parameters
Passing by Value
Passing by Address
Passing by Reference
Passing by Const Reference
PASSING BY VALUE
int x;
Formal parameter x is a local variable
It is the duplicate of the actual parameter
It cannot change the actual parameter
Actual parameter may be a constant, a variable or
an expression
Actual parameter is read-only
Pass byvalueis appropriate forsmallobjects that
shouldnotbe changed by the function
PASSING BY ADDRESS
int *p;
Formal parameter p is a local pointer
It is the address for the actual parameter
It can change the actual parameter
Actual parameter must be address of identifier
Actual parameter is read-write
Pass by address is appropriate for all objects that
may be changed by the function
PASSING BY REFERENCE
int &r;
Formal parameter r is a local reference
It is a synonim for the actual parameter
It can change the actual parameter
Actual parameter must be a variable
Actual parameter is read-write
Pass by referenceis appropriate for all objects that
may be changed by the function
PASSING BY CONST REFERENCE
Same as passing by reference except that the
function is prevented from changing the value of the
parameter
Actual parameter is read-only
Pass by constant referenceis appropriate
forlargeobjects that shouldnotbe changed by the
function
EXAMPLE: PASSING BY VALUE
Formal parameter
void calculate (int a, int b){
a = a+ 1;
int c = a + b;
cout < < "c = " < < endl;
}
int m ain(){
int x = 1, y = 2; Actual parameter
calculate (x, y);
cout < < "x = "< < x;
cin.get();
return 0;
}
EXAMPLE: PASSING BY ADDRESS
void calculate (int *a, int *b){
*a = *a+ 1;
int c = *a + *b;
cout < < "c = " < < endl;
}
int m ain(){
int x = 1, y = 2;
calculate (& x, & y);
cout < < "x = "< < x;
cin.get();
return 0;
}
EXAMPLE: PASSING BY REFERENCE
void sw ap(int& x, int& y) {
int tem p = x;
x = y;
y = tem p;
}

int m ain() {
int a = 19,b = 47;
cout < < a < < " " < < b < < endl;
sw ap (a,b);
cout < < a < < " " < < b < < endl;
cin.get();
return 0;
}
EXAMPLE: PASSING BY CONST REFERENCE
void calculate (const int & a, const int & b){
a = a+ 1; //error : cannot m odify const object
int c = a + b;
cout < < "c = " < < endl;
}
int m ain(){
int x = 1, y = 2;
calculate (x, y);
cout < < "x = "< < x;
cin.get();
return 0;
}
Q&A
References
Deitel, P., & Deitel, H. (2012). C++ How to Program.8 th
edition. New Jersey: Prentice Hall. Chapter 6 & 8
THANK YOU

Das könnte Ihnen auch gefallen