1
Structure of a C++ Program
↑ Index
C++
Every C++ program starts running from main(). Header files bring in library code, and using namespace std; lets us write cout instead of std::cout.
C++
#include <iostream> // header for input / output
using namespace std; // use names from std without std::
int main() { // execution starts here
int age;
cout << "Enter age: ";
cin >> age; // input
cout << "Age is " << age << endl; // output
return 0; // 0 = program ended successfully
}
- #include is a preprocessor directive; it copies the header in before compiling.
- cin uses
>> (extraction), cout uses << (insertion). endl adds a new line and flushes the buffer; "\n" only adds a new line (faster).
Q & A
- What is the difference between C and C++?
C is procedural. C++ adds object-oriented programming (classes, inheritance, polymorphism), references, function overloading, templates, exceptions and the STL.
- Why does main() return int?
The return value goes to the operating system. 0 means success, any other value means an error.
2
Data Types and Sizes
↑ Index
C++
| Type | Size (typical) | Range / Use |
|---|
| bool | 1 byte | true / false |
| char | 1 byte | -128 to 127, one character |
| int | 4 bytes | about ±2.1 × 109 |
| long long | 8 bytes | about ±9.2 × 1018 |
| float | 4 bytes | ~7 decimal digits |
| double | 8 bytes | ~15 decimal digits |
| string | varies | text (std::string) |
C++
cout << sizeof(int) << endl; // 4
cout << sizeof(long long) << endl; // 8
cout << INT_MAX << endl; // 2147483647 (needs <climits>)
Type casting: (double)a / b or static_cast<double>(a) / b gives a decimal result; a / b with two ints drops the fraction.
C++
A pointer stores the memory address of another variable. & gives an address, * reads the value at an address (dereference).

p holds the address of x, so *p gives the value of x
C++
int x = 10;
int *p = &x; // p stores the address of x
cout << p; // address, e.g. 0x7ffe10
cout << *p; // 10
*p = 20; // changes x through the pointer
cout << x; // 20
int *q = nullptr; // points nowhere (always initialise pointers)
Pointer and array · C++
int arr[] = {10, 20, 30};
int *p = arr; // array name = address of first element
cout << *(p + 1); // 20 (pointer arithmetic)
Q & A
- What is a null pointer?
A pointer that points to nothing (nullptr). Dereferencing it crashes the program, so check before use.
- What is a dangling pointer?
A pointer that still holds the address of memory that has already been freed or has gone out of scope.
- What is a void pointer?
A generic pointer (void*) that can hold the address of any type, but must be cast before dereferencing.
4
Reference vs Pointer
↑ Index
C++
A reference is another name (alias) for an existing variable.
C++
int x = 10;
int &r = x; // r is another name for x
r = 50;
cout << x; // 50
| Reference | Pointer |
|---|
| Must be initialised when declared | Can be declared without a value |
| Cannot be null | Can be nullptr |
| Cannot be changed to refer to another variable | Can point to another address later |
| No special syntax to access (r) | Needs * to access (*p) |
5
Call by Value vs Call by Reference
★★★★★
↑ Index
C++
Call by value passes a copy, so changes inside the function do not affect the caller. Call by reference passes the variable itself.
C++
void byValue(int a) { a = 100; }
void byReference(int &a) { a = 100; }
void byPointer(int *a) { *a = 100; }
int main() {
int x = 1;
byValue(x); cout << x; // 1 (copy changed)
byReference(x); cout << x; // 100
x = 1;
byPointer(&x); cout << x; // 100
}
Tip: pass large objects as const T& to avoid copying and to stop accidental changes.
6
Function Overloading
↑ Index
C++
Several functions with the same name but different parameter lists (number or type). The compiler picks the right one at compile time (compile-time polymorphism).
C++
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
add(2, 3); // 5
add(2.5, 1.5); // 4.0
add(1, 2, 3); // 6
Note: a different return type alone is not enough to overload.
7
Dynamic Memory (new / delete)
↑ Index
C++
new allocates memory on the heap at run time; delete frees it. Forgetting delete causes a memory leak.

Local variables live on the stack, new allocates on the heap
C++
int *p = new int(5); // single int on heap
delete p;
int n = 5;
int *arr = new int[n]; // array on heap
delete[] arr; // use delete[] for arrays
// Modern C++: smart pointers free memory automatically
unique_ptr<int> u = make_unique<int>(10); // needs <memory>
Q & A
- malloc vs new?
malloc is a C function that returns void* and does not call constructors. new is a C++ operator, returns the correct type and calls the constructor; delete calls the destructor.
8
STL: vector, map, set
★★★★★
↑ Index
C++
The Standard Template Library gives ready-made containers and algorithms.
vector (dynamic array) · C++
vector<int> v = {3, 1, 2};
v.push_back(4); // add at end
sort(v.begin(), v.end()); // 1 2 3 4
cout << v.size(); // 4
for (int x : v) cout << x << " ";
map (key → value) · C++
map<string, int> age; // sorted by key
age["Rahim"] = 25;
age["Karim"] = 30;
for (auto &[name, a] : age)
cout << name << " " << a << endl;
if (age.count("Rahim")) cout << "found";
set (unique, sorted) · C++
set<int> s = {5, 1, 5, 3}; // unique and sorted: 1 3 5
s.insert(2);
cout << s.count(5); // 1 = present
| Container | Lookup | Notes |
|---|
| vector | O(1) by index | Contiguous, push_back amortised O(1) |
| map / set | O(log n) | Red-black tree, keeps keys sorted |
| unordered_map / set | O(1) average | Hash table, no order |
| stack / queue | top/front O(1) | Adapters for LIFO / FIFO |
| priority_queue | top O(1), push O(log n) | Max-heap by default |
9
String Functions
↑ Index
C++
C++
string s = "Hello World";
s.length(); // 11
s.substr(0, 5); // "Hello"
s.find("World"); // 6 (string::npos if not found)
s += "!"; // append
s.replace(0, 5, "Hi"); // "Hi World!"
toupper(s[0]); // single char to upper case
stoi("123"); // string → int
to_string(456); // int → string
getline(cin, s); // read a full line with spaces
10
const, static and inline
↑ Index
C++
- const — value cannot change after initialisation. A
const member function cannot modify the object. - static local variable — keeps its value between function calls.
- static member — one copy shared by all objects of the class.
- inline — asks the compiler to paste the function body at the call site to avoid call overhead (for small functions).
C++
void counter() {
static int count = 0; // initialised only once
count++;
cout << count << " ";
}
// counter(); counter(); counter(); → 1 2 3
C++
Templates let one function or class work with any data type (generic programming). The STL is built on templates.
C++
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
getMax(3, 7); // 7
getMax(2.5, 1.5); // 2.5
getMax<char>('a', 'z');
12
Exception Handling
↑ Index
C++
Errors are thrown with throw and caught with try / catch, so the program does not crash.
C++
int divide(int a, int b) {
if (b == 0) throw runtime_error("Division by zero");
return a / b;
}
try {
cout << divide(10, 0);
} catch (const exception &e) {
cout << "Error: " << e.what();
}