1. Input / Output

Definition – Standard streams

A program that uses the standard input/output streams must include the I/O library.

StreamRoleUsually attached to
cinstandard inputkeyboard
coutstandard outputscreen
cerrstandard error (error messages)screen

Insertion and extraction operators

  • << is the insertion operator: inserts data into an output stream. Works for any type (char, int, float, string…) — no format specifiers needed.
  • >> is the extraction operator: extracts data from an input stream and stores it in variables.
cout << expr1 << expr2 << expr3;   // several outputs
cout << endl;                      // new line
cin  >> var1 >> var2 >> var3;      // reads values into var1, var2, var3 in order

Worked example

#include <iostream>
using namespace std;
int main() {
    int age; float gpa;
    cout << "Age and GPA: ";
    cin >> age >> gpa;            // user types: 20 3.4
    cout << "Age=" << age << ", GPA=" << gpa << endl;
}

Output: Age=20, GPA=3.4

⚠️ The slide writes #include <iostream.h> — that is pre-standard C++ and won’t compile on modern compilers. Use #include <iostream> + using namespace std;.


2. Memory Addresses and the Address Operator

Definition – Memory address

Memory is a huge array of bytes; the index of each byte (written in hexadecimal) is its address. Declaring a variable associates three attributes:

  1. a name,
  2. a type,
  3. a memory address where its value lives.

int a; → name a, type int, an address of (usually) 4 consecutive bytes.

Definition – Address (reference) operator &

Placed immediately before a variable, & returns the variable’s address.

Worked example

int a = 5;
cout << "a=" << a << endl;               // a=5
cout << "address of a=" << &a << endl;   // address of a=0x00000010 (machine-dependent)

3. Pointers

Definition – Pointer

A pointer is a variable that stores a memory address (of another variable). Declaration: type pointed to, then *, then the name.

char *cp;   // pointer to a char
int  *ip;   // pointer to an int
  • The * after the type means “this variable holds an address of a value of that type”, not the value itself.
  • The format of an address is the same whatever the pointed type.

⚠️ int* p1, p2; declares one pointer (p1) and one plain int (p2). Write int *p1, *p2;.

Pointer arithmetic

Adding/subtracting an integer moves the pointer by a multiple of the size of the pointed type:

Worked example (4-byte int, 1-byte char)

ExpressionAddress
ip0x10
ip + 10x14
ip + 20x18
cp0x20
cp + 10x21

Reference & and dereference * operators

  • &x → address of x (used to initialize a pointer: int *ip = &i;).
  • *ip (outside a declaration) → the content of the memory cell pointed to by ip.
flowchart LR
    ip["ip = 0x0012FF7C"] -- points to --> i["i = 5 (at 0x0012FF7C)"]
int i = 5;
int *ip = &i;
cout << "The content referenced by ip = " << *ip;   // 5

Worked example – pointer trace (slide 11)

int i = 5, j;
int *ip = &i;
*ip = *ip + 7;
j = *ip + 1;
Stepijip*ip
int *ip = &i;5?&i5
*ip = *ip + 7;12?&i12
j = *ip + 1;1213&i12

Changing *ip changes i itself, because ip points to i.

Pointer assignment vs content assignment

StatementMeaning
p1 = p2;p1 now points to the same object as p2 (addresses copied)
*p1 = *p2;the value pointed by p2 is copied into the object pointed by p1

Worked example – start: p1 → 8, p2 → 9

flowchart LR
    subgraph S1 ["p1 = p2"]
    a1[p1] --> b9a[9]
    a2[p2] --> b9a
    b8a["8 (no longer referenced by p1)"]
    end
    subgraph S2 ["*p1 = *p2"]
    c1[p1] --> d9["9 (was 8)"]
    c2[p2] --> d9b[9]
    end

Pointer comparison

if (p1 == p2)   // same address?
if (*p1 == *p2) // same content?

4. Dynamic Allocation

Definition – new / delete

A pointer must be initialized with a valid address before use. Three ways:

  1. int *p1 = &i; (address operator)
  2. p1 = p2; (copy of an already-initialized pointer)
  3. p1 = new int; — dynamic allocation: reserves memory at run time for an object and returns its address.

delete p; frees the memory pointed to by p (not p itself) so it can be reused. Every new should be matched by a delete.

Worked example (slide 15)

int *p1, *p2;
p1 = new int;  *p1 = 42;
p2 = p1;
*p2 = 53;
p1 = new int;  *p1 = 88;
Step*p1*p2Comment
p1 = new int; *p1 = 42;42–block A created
p2 = p1;4242both point to A
*p2 = 53;5353A changed through p2
p1 = new int; *p1 = 88;8853p1 → new block B, p2 still → A

⚠️ The example never calls delete → both blocks leak. Add delete p1; delete p2; at the end.

Dynamic arrays

int *p = new int[5];
p[0] = 1;        // same as *p
p[1] = 2;        // same as *(p+1)
delete[] p;      // array form of delete

⚠️ Use delete[] for memory obtained with new[] and delete for new. Mixing them is undefined behavior.


5. Passing Parameters

ModeSyntaxEffect on the caller’s variable
By valuevoid f(int a)function works on a copy → unchanged
By referencevoid f(int &a)a is an alias of the argument → changed

Worked example

void PassingValue(int a)      { a++; }
void PassingReference(int &a) { a++; }
 
int k = 10;
PassingValue(k);      // k = 10
PassingReference(k);  // k = 11

6. Templates

Definition – Template

Templates are the basis of generic programming: code written independently of a specific type, then instantiated for a type (e.g. one Stack class usable for int, char, …).

template <class T, ...> class X { ... };

Class template – one parameter

template <class T>
class X {
public:
    T max(T a, T b) { return (a > b) ? a : b; }
};
 
X<int> x;
int k = x.max(5, 2);   // 5

Class template – two parameters

template <class T, class U>
class X2 {
    T a; U b;
public:
    void assign(T a, U b) { this->a = a; this->b = b; }
    void display() { cout << a << " " << b << endl; }
};
 
X2<int, char> x;
x.assign(5, 'k');
x.display();           // 5 k

Templates and inheritance

A template class can derive from another template class; methods can be defined outside the class with the full template header:

template <class T, class U>
class Y : public X2<T, U> {
    U c;
public:
    Y(T a, U b, U ic) { this->assign(a, b); c = ic; }
    ~Y() { c = 0; }
    void displayY();
};
 
template <class T, class U>
void Y<T, U>::displayY() { cout << c << endl; }

⚠️ The slide calls assign(a,b); directly inside Y. Because the base X2<T,U> depends on template parameters, standard C++ won’t find it — write this->assign(a, b); (as above).

Function templates

template <class T>
T max(T a, T b) { return (a > b) ? a : b; }
 
int   k = max<int>(5, 2);          // 5
float n = max<float>(10.2f, 4.5f); // 10.2

⚠️ With using namespace std;, a user-defined max clashes with std::max → “ambiguous call” error. Rename it (e.g. myMax) or drop using namespace std;.