Lecture 2 OOP Spring 2025
Lecture 2 OOP Spring 2025
Contents:
• Pass by Value/References
• Pointers as Parameter
• Constant Pointers Lecture 2
Usman Anwer
Lecturer
Spring-2025
Task
Assume pint is a pointer variable. Is each of the following statements valid or
invalid? If any is invalid, why?
A) pint++;
B) −−pint;
C) pint /= 2;
D) pint *= 4;
E) pint += x; // Assume x is an int.
Which one is Valid?
int ages[20];
int *pint = ages;
OR
float myFloat;
int *pint = &myFloat;
Comparing Pointers
int main()
{
int a = 10;
modifyValue(a);
cout << "Value of a after function call: " << a << endl;
return 0;
}
Array as an Argument
void sum(int array[], int size) {
for (int i = 0;i < size;i++) {
array[i] = array[i] + 5;
} }
}
Pointers as Function Parameters
sum += *arr;
main():
arr++; const int QTRS = 4;
double sales[QTRS];
} return sum; } getSales(sales, QTRS);
totalSales(sales, QTRS)
sum += *arr++;?
Pointer to Constants
Example 1:
const int val = 23; // Constant variable
const int* ptr=&val; // Pointer to constant variable
*ptr = *ptr * 2; //ERROR; Cannot be modified
Example 2:
int abc = 23; // Integer variable
const int* ptr1=&abc; //Constant pointer to non-constant variable
*ptr1 = *ptr1 * 2; // ERROR; Cannot be modified
Pointer to Constants
Example 3:
const int val = 23; // Constant variable
int* ptr=&val; // ERROR! Pointer to constant variable
Summary is:
• Constant pointer can hold reference of constant variable.
• Constant pointer can also hold the reference of non-constant
variable.
• Non-Constant pointer cannot hold the reference of constant variable.
• Pointers to constant variables can change its reference.
Constant Pointers
Constant pointers refer to pointers that cannot change the address
they are pointing to after initialization but value can be changed.
int* invalidFunction() {
int x = 10; // Local variable
return &x; // Returning address of a local variable
}
Memory Allocations to Pointers
int* allocateMemory() {
int* ptr = new int(42); // Dynamically allocate memory
return ptr;
}
Questions
• Difference between:
const int* ptr
int* const ptr
const int* const ptr
• What happens if you return a pointer to an automatic (local) variable
from a function?
• Difference between a pointer and a reference?
Pointer vs Reference
Class Task
Write a function that performs pointer arithmetic to
reverse an array in place. The function should not
use array indexing (arr[1])?