03.POINTERS

SYNTAX

dataType *pointerID;

EXAMPLE

//p is a pointer to a memory location of type integer
//*p will contain actual data
int *p
 * ALT: int* p
 
//p is a pointer to a memory location of type integer
//q is a regular variable
int *p, q

//p & q are pointers to a memory location of type integer
int *p, *q

DEFINITIONS

POINTERS

  • variables whose content is a memory address/location

  • C++ doesn't automatically initializes pointer variables

    • use the following to initializes pointer variables

ADDRESS OF OPERATOR (&)

  • the "&" is a unary operator that returns the "address of" its operand

ASSIGNING MEMORY LOCATIONS

  • CAVEAT: the two instructions below are different! you can't use the & operator using two pointers

OPERATIONS ON POINTER VARIABLES

DYNAMIC VARIABLES

  • these are variables that are created during a program's execution

  • can be created with the help of pointers

  • uses the operators "new" and "delete"

    • the "new" operator is used to create dynamic variables

      • it allocates memory of the desired type & returns a pointer (the address) to it

    • the "delete" operator is used to delete dynamic variables

STATIC VARIABLES

  • these are variables that are created prior to a program's execution (think pre-loaded)

DYNAMIC ARRAYS

  • created during program execution

STATIC ARRAYS

  • fixed size; everytime a program executes, the size of the array is fixed (limitation of static array)

FUNCTIONS & POINTERS

  • pass-by-value

  • pass-by-reference

ISSUES WITH CLASSES & POINTERS

  • if one gets deleted, then all are deleted

    • to resolve this issue, overload the assignment operator IOT have two copies

one deletes/destroys the other since they are pointing to the same location
visual representation of the assignment operator overloading which resolves classes & pointers issue

DYNAMIC VARIABLES IMPLEMENTATION

OBJECT POINTERS IMPLEMENTATION

OVERLOADING THE ASSIGNMENT OPERATOR IMPLEMENTATION

SOURCE FILE: pointers.cpp

Last updated