Lecture 3
Lecture 3
Paradigms in C++
CSCI 3142
By
Priyanka Samanta
Reference in C++
A reference defines an alternative names for an object. A reference type
“refers to” another object. Once a reference is initialized with a variable, either
the variable name or the reference name may be used to refer to the variable.
▪ You cannot have NULL references. You must always be able to assume that
a reference is connected to a legitimate piece of storage.
▪ Once a reference is initialized to an object, it cannot be changed to refer to
another object. (java is more flexible)
▪ A reference must be initialized when it is created.
Reference definition
&d, where d is the name of the reference
int i = 17;
int& r = i; //r is an integer reference initialized to I
Note: When we define a reference, instead of copying the initializer’s value, we bind the
reference to it’s initializer.
Why we need a reference?
The main use of references is acting as function formal parameters to support
pass-by-reference. In a reference variable is passed into a function, the
function works on the original copy (instead of a clone copy in pass-by-value).
Changes inside the function are reflected outside the function.
Important: After a reference has been defined, all operations on that reference are actually
operations on the object to which the reference is bound!
Reference vs Pointer
• You cannot have NULL references. You must always be able to assume that a reference
is connected to a legitimate piece of storage. A pointer is an object of its own right.
• Once a reference is initialized to an object, it cannot be changed to refer to another
object. Pointers can be pointed to another object at any time.
• A reference must be initialized when it is created. Pointers can be initialized at any
time.
Pointer definition
*d, where d is the name of the pointer
What do pointers hold?
A pointer holds the address of another object
We get the address of an object using address of operator (&)
Pointer initialization & dereferencing
*++p // same as *(++p): move the pointer, and then read the data
++*p // same as ++(*p): Read the data, and increment the value it points to
Pointers and heap memory
and dynamic array
• Dynamic array size can be changed unlike fixed array
• Dynamic array is created using “new” keyword
• Dynamic array is created in heap memory which is dynamically allocated using run
time, not at compile time
• Fixed size array created in stack and gets automatically deleted once goes out of
scope
• Dynamic array does not get deleted and will be available as long as the program is
running
• Using pointer, we can access dynamic array created in heap (unlike Java)
• Can cause memory leak, if not handled properly
C++ dynamic array
Code link: https://replit.com/@SamantaPriyanka/Pointer-and-
reference#dynamicArray_pointer.cpp
Multidimensional dynamic array