C++ Language Extensions: References, Dynamic Memory & Stream Manipulators
Idea in plain words
Reference Variables (int &ref = var): An alias or alternative name for an existing variable; cannot be null and cannot be reseated after initialization.
Explanation
C++ extends C with strong typing, safe pointer aliases, and type-safe heap management. While malloc() allocates uninitialized raw bytes and requires manual type casting, new allocates typed memory and guarantees automatic object lifecycle initialization.
Key points
- Dynamic Memory: new and delete operators allocate and deallocate heap memory, automatically invoking constructors and destructors (unlike malloc/free).
- Scope Resolution Operator (::): Accesses global variables obscured by local scope, and defines member functions outside class declarations.
- Stream Manipulators: endl (newline + flush), setw(n) (sets field width), setprecision(n) (formats floating-point decimals in ).
Example
Example
Call by reference using reference parameters void swap(int &a, int &b) avoids the pointer syntax *a and *b while still enabling in-place mutation of caller variables.
Code examples
// References, Scope Resolution & Dynamic Memory in C++
#include <iostream>
#include <iomanip>
using namespace std;
int globalCount = 500;
int main() {
int globalCount = 10;
cout << "Local: " << globalCount << ", Global via :: : " << ::globalCount << endl;
// Dynamic Array Allocation
int n = 5;
int *arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = (i + 1) * 10;
cout << "Formatted output: " << setw(8) << setprecision(2) << fixed << 123.4567 << endl;
delete[] arr; // Crucial to prevent heap memory leak
return 0;
}
Exam questions
- [7 Marks] Differentiate between pointers and reference variables in C++. Write a program demonstrating pass-by-reference.
- [7 Marks] Explain dynamic memory allocation in C++. Contrast new/delete with malloc/free.