BME Course
C & C++

Programming 2

Programming 1 but you can't study the night before and memorize all the questions.

0/19

Weeks

43

Topics

30

Videos

36

Quizzes

Course Blocks

All Weeks

Module 1

First Programs

Alright, so you are about to write your very first programs — exciting, right? But before we jump into building anything fancy, let's talk about what actually happens when you type some code and hit "run." Like, what is really going on behind the scenes? Think of it this way: imagine you want to invent a brand new language — like an actual human language. What would you need? An alphabet, some grammar rules, a way to structure sentences, right? Programming languages work the same way. **C** is the language (with its own rules and grammar), and the **compiler** is the tool that checks if you followed those rules correctly and then translates everything into something the computer can actually understand — binary, the 1s and 0s. This week, we are going to cover three big things. First, **how your code becomes a program** — you write a text file, a tool called a compiler translates it, and boom, you have something that runs. Second, **variables and data types** — think of these as labeled boxes where you stash your data (numbers, letters, decimals) while your program does its thing. Third, **input and output** — how your program talks to the user with `printf` and listens with `scanf`. | Concept | What It Means | Why It Matters | |---------|--------------|----------------| | Source Code | The `.c` file you write in C | It is your set of instructions in human-readable form | | Compiler (gcc) | Translates source code to machine code | The computer cannot read C directly — it needs binary | | Variable | A named box in memory that holds a value | Every program needs to store and manipulate data | | Data Type | The kind of value a variable holds (int, float, char) | Tells the computer how much memory to reserve and how to interpret the bits | | printf/scanf | Functions for output and input | How your program communicates with the user |

3 topics2 videos2 quizzes
Module 2

Control Flow & Functions

So last week, your programs were pretty straightforward — they just ran from the first line to the last line, one after the other. Every single instruction got executed exactly once. But think about it... real programs do not work that way, right? They need to make choices — like "if this user is old enough, let them in, otherwise show an error." And they need to repeat things — like "keep asking for a password until they get it right." That is what this week is all about. We are learning two of the most powerful ideas in programming: **conditional statements** (making decisions) and **loops** (repeating things). On top of that, we will get into **functions** — which are basically reusable chunks of code that you give a name to. Instead of copy-pasting the same code everywhere, you write it once, put it in a function, and just call it whenever you need it. We will even touch on **recursion** — which is when a function calls itself. Sounds wild, but it is actually a really elegant way to solve certain problems. | Concept | What It Does | Real-World Analogy | |---------|-------------|--------------------| | `if/else` | Makes decisions based on conditions | A traffic light — go if green, stop if red | | `for` loop | Repeats code a known number of times | Counting laps around a track | | `while` loop | Repeats code until a condition becomes false | Stirring soup until it boils | | Function | A reusable block of code with a name | A recipe you can follow whenever you need it | | Recursion | A function that calls itself | Russian nesting dolls — each doll contains a smaller version of itself |

3 topics2 videos2 quizzes
Module 3

Introduction to C++ & Strings

Alright, big moment — this week you are making the jump from **C** to **C++**. Now, do not worry, you are not throwing away everything you learned. C++ is basically C with superpowers. Almost all the C code you have written so far is also valid C++. Think of it like this: if C is a bicycle, C++ is that same bicycle but with an electric motor strapped on. Everything you already know still works, you just have some really nice extras now. So what are these extras? Three big ones this week. First, **`cout` and `cin`** replace `printf` and `scanf` — and honestly, they are so much nicer. No more memorizing format specifiers like `%d` or `%f` — C++ figures out the type for you automatically. Second, the **`std::string` class** replaces those awkward C-style `char` arrays. Strings in C++ can grow on their own, you can smash them together with `+`, compare them with `==`, and use handy methods like `.length()`, `.substr()`, and `.find()`. Third, you will learn about **namespaces**, which is C++'s way of keeping code organized so names do not clash — the `std` namespace is where all the standard library stuff lives. | C Way | C++ Way | Why C++ Is Better | |-------|---------|--------------------| | `printf("%d", x);` | `cout << x;` | No format specifiers needed — type is detected automatically | | `scanf("%s", name);` | `cin >> name;` | No `&` needed, and no buffer overflow risk with `string` | | `char name[50];` | `string name;` | No fixed size — strings grow and shrink as needed | | `strcmp(a, b) == 0` | `a == b` | Direct comparison with `==` instead of a function call | | `strcat(a, b);` | `a + b` | Concatenation with the `+` operator | By the end of this week, you will be writing cleaner, more modern code using C++ I/O streams, the string class, and namespaces. The tedious and error-prone C-style string handling? You are leaving that behind.

3 topics2 videos2 quizzes
Module 4

Functions in C++ (Deep Dive)

Alright, so you already know how to write a basic function in C, right? You pick a return type, give it a name, throw in some parameters, and write the body. Cool. But what if I told you that C++ lets you do some seriously powerful things with functions that C just... can't? That's what this week is all about — leveling up your function game. Let's start with something that probably annoyed you in C. Say you want an `add` function for integers, and another one for doubles. In C, you'd have to name them differently — `addInt()`, `addDouble()`, whatever. Ugly, right? Well, C++ says "nah, just call them both `add`" — and the compiler figures out which one you meant based on what you pass in. That's called **function overloading**, and it's our first big topic. Then we've got **default parameters** and **pass-by-reference**. Default parameters are like fallback values — think of it like this: if someone doesn't tell you their name, you just say "Hello, World!" instead. And pass-by-reference (that little `&` symbol) lets your function reach out and actually change the original variable, instead of just playing with a copy. We'll also dig into **scope and lifetime** — basically, where can your variable be seen, and how long does it stick around in memory? | Feature | What It Does | Example | |---------|-------------|--------| | Function Overloading | Same function name, different parameter types/counts | `int add(int, int)` and `double add(double, double)` | | Default Parameters | Arguments with fallback values if not provided | `void greet(string name = "World")` | | Pass-by-Reference | Function modifies the caller's original variable | `void doubleIt(int& x)` | | Const Reference | Avoids copying without allowing modification | `void print(const string& s)` | | Static Local | Variable that persists between function calls | `static int count = 0;` | By the end of this week, you'll be writing functions that are cleaner, more flexible, and way more efficient than anything you could pull off in plain C. Let's get into it.

3 topics2 videos3 quizzes
Module 5

Vectors & the STL

So far, when you needed a list of values in C, you used arrays. And let's be honest... arrays in C are kind of a pain. You have to decide the size upfront, they don't know how long they are, and if you accidentally access an element that doesn't exist? No error message — just a crash or weird data corruption. Fun times. This week, we're saying goodbye to all that nonsense and hello to **`std::vector`** — C++'s answer to "what if arrays were actually good?" A vector is basically a **dynamic array** that grows and shrinks whenever you need it to, always knows exactly how many elements it has, and can even warn you if you try to access something out of bounds. We've got three big things to cover. First, **vector basics** — creating them, adding stuff with `push_back`, accessing elements, removing them. Second, **range-based for loops** — a clean, modern way to loop through everything in a container without dealing with indices. And third, **STL algorithms** — pre-built, battle-tested functions from the **Standard Template Library** that can sort, reverse, search, count, and sum your data with a single function call. Why write your own sort when the C++ experts already wrote one that's faster than yours would be? | Feature | C Array | C++ Vector | |---------|---------|------------| | Size | Fixed at compile time | Dynamic — grows and shrinks at runtime | | Knows its length? | No — you must track it separately | Yes — `v.size()` returns the count | | Bounds checking? | No — out-of-bounds access causes silent bugs | Optional — `v.at(i)` throws an exception if `i` is invalid | | Adding elements | Not possible (fixed size) | `v.push_back(value)` adds to the end | | Works with STL algorithms? | Yes, but awkward | Yes — naturally integrates with `sort`, `find`, etc. | The **STL (Standard Template Library)** is honestly one of the best things about C++. It gives you ready-made, heavily optimized data structures and algorithms so you don't have to reinvent the wheel. By the end of this week, you'll be managing collections of data like a pro.

3 topics2 videos2 quizzes
Module 6

Structs, Enums & Data Organization

Alright, let's think about something. So far, you've been storing data in separate variables — an `int` for age, a `string` for name, a `double` for GPA. That works fine for one student. But what happens when you need to keep track of 100 students? Are you going to create 300 separate variables? Yeah, that would be a nightmare. This is where **structs** come in, and they're going to change the way you think about organizing data. A **struct** (short for structure) lets you **bundle related variables together** under one name, essentially creating your own custom data type. Think of it like a form or a record card — a student card has fields for name, age, and GPA, all on one card. You can then have a whole stack of these cards (which, in code, is just a vector of structs). We'll also learn about **`enum class`** — a way to create variables that can only hold specific, named values. Instead of using random integers like `0`, `1`, `2` to represent colors (which is confusing and error-prone), you define `enum class Color { Red, Green, Blue };` and write `Color c = Color::Red;`. Way more readable, and it prevents bugs where you accidentally assign something invalid. | Concept | What It Solves | Example | |---------|---------------|--------| | Struct | Groups related data into one custom type | `struct Student { string name; int age; double gpa; };` | | Struct methods | Lets structs have their own functions | `void display() const { cout << name; }` | | Enum class | Restricts a variable to a fixed set of named values | `enum class Color { Red, Green, Blue };` | | Vector of structs | Manages a collection of structured records | `vector<Student> roster;` | By the end of this week, you'll be designing your own data types, storing collections of structured data in vectors, and using type-safe enumerations to make your code cleaner. And here's the exciting part — structs are the stepping stones to **classes and object-oriented programming**, which we'll tackle in later weeks.

3 topics2 videos2 quizzes
Module 7

File I/O & Robust Programs

So here's the thing — every program you've written so far has a pretty big problem. You run it, you enter all this data, maybe 50 grades into a vector... and then you close the terminal. Poof. Gone. All of it. It's like writing a whole essay on a whiteboard and then someone erases it the moment you walk away. Wouldn't it be nice if your program could actually *remember* things? That's what this week is all about — making your data **persistent** by saving it to **files** on disk, and also learning how to build **robust programs** that don't just crash when something unexpected happens. We're going to cover three big skills here. First, **file I/O** — reading from and writing to files using **`ofstream`** and **`ifstream`**. And here's the cool part: if you already know `cout` and `cin`, you basically already know file I/O. Same `<<` and `>>` operators, just pointed at a file instead of the screen. Second, we'll get into **parsing with `stringstream`** — think of it as a tool that lets you rip apart structured text like CSV data (you know, those comma-separated files) into individual pieces you can actually use. Third, **input validation and error handling** — because users *will* type "abc" when you ask for a number, and your program needs to deal with that gracefully using things like `cin.fail()`, `cin.clear()`, `cin.ignore()`, and `try/catch`. | Concept | What It Does | Key Class/Function | |---------|-------------|-------------------| | Writing files | Saves data to a file on disk | `ofstream outFile("data.txt");` | | Reading files | Loads data from a file on disk | `ifstream inFile("data.txt");` | | Parsing strings | Splits structured text into typed values | `stringstream ss(line);` | | Input validation | Detects and recovers from bad user input | `cin.fail()`, `cin.clear()`, `cin.ignore()` | | Exception handling | Catches and handles runtime errors gracefully | `try { ... } catch (exception& e) { ... }` | By the end of this week, your programs will be able to save stuff to files, load it all back, chop up structured text like CSV, and handle errors without blowing up. These are honestly skills you'll use every single day as a programmer — let's get into it.

3 topics2 videos2 quizzes
Week 1

C++ & References

Alright, big moment — this week you're making the jump from **C** to **C++**. And don't worry, it's not like learning a whole new language from scratch. Think of it like this: C is like driving a manual car, and C++ is like upgrading to an automatic with cruise control. Everything you already know still works, but now you've got extra features that make your life a lot easier and your code a lot safer. We're covering two major things. First, **C++ I/O with `cout` and `cin`** — the new way to print output and read input. Remember `printf` and `scanf` with all those format specifiers like `%d`, `%f`, `%s`? Yeah, you can forget about those. C++ figures out the type automatically. Way less room for mistakes. Second, you'll learn about **references** — basically a way to create another name for an existing variable. But why would you want that? Because references are the key to **pass-by-reference**, which lets functions modify the caller's variables directly instead of just working with a copy. | C Style | C++ Style | What Changed | |---------|-----------|-------------| | `printf("%d", x);` | `cout << x;` | No format specifiers needed | | `scanf("%d", &x);` | `cin >> x;` | No `&` needed for basic types | | Pass by pointer (`int* p`) | Pass by reference (`int& r`) | Cleaner syntax, same effect | By the end of this week, you'll be writing C++ programs with modern I/O and you'll understand why references are one of the most important things C++ brings to the table.

2 topics2 videos1 quizzes
Week 2

Arrays & Pointers

Alright, buckle up — this week we're diving into **pointers**, and yes, it's one of those topics that trips a lot of people up at first. But don't worry, we'll break it down so it actually makes sense. So what's a pointer? It's a variable that, instead of holding a value like `42`, holds the *address* where `42` lives in memory. Think of it like this: instead of having the pizza, you have the delivery slip that tells you where the pizza is. Understanding pointers is essential because they're the foundation of dynamic memory, data structures like linked lists and trees, and efficient function calls. We're covering two connected topics. First, **Pointer Basics** — how to declare them, how to get a variable's address with **`&`** (the address-of operator), and how to access the value at an address with **`*`** (the dereference operator). Second, **Arrays and Pointer Arithmetic** — the deep, almost secret connection between arrays and pointers. You'll find out that an array name is basically just a pointer to its first element, and you can navigate through an array by doing math on pointers. Imagine your computer's memory as a long row of numbered mailboxes. Each mailbox has an **address** (its number) and holds a **value** (the mail inside). A pointer is like a sticky note that says "go check mailbox #2048." It doesn't hold the value directly — it tells you where to find it. After this week, you'll think about memory in a whole new way, and you'll have the low-level control that makes C/C++ so powerful.

2 topics2 videos1 quizzes
Week 3

Dynamic Memory

So far, every variable you've declared had its size decided at **compile time** — you write `int arr[100];` and the compiler bakes that 100 right into your program. But what if you don't know how many elements you'll need until the program is already running? What if a user wants to store 5 items today and 50,000 tomorrow? You can't just hardcode that. This is where **dynamic memory allocation** enters the picture — you're asking the operating system at **runtime**: "Hey, can I borrow some memory?" This week is all about understanding **where** your data lives and **how** to manage memory yourself. First, we'll explore the two zones of memory your program uses — the **stack** (fast, automatic, but small) and the **heap** (big, flexible, but you're in charge of cleanup). Think of the stack as your desk and the heap as a giant warehouse — you can grab as much space from the warehouse as you want, but nobody's cleaning up after you. Then we'll dive deep into the **C way** of managing memory: **`malloc()`** to request memory, **`free()`** to give it back, plus **`calloc()`** for zero-initialized blocks and **`realloc()`** to resize on the fly. These are the classic tools — and understanding them is essential because they're the foundation that C++ builds on. Once you've got the C approach down, we'll look at how C++ improves things with **`new`** and **`delete`**, which are cleaner and type-safe. Finally, we'll cover the **three deadly sins** of memory management: **memory leaks** (forgetting to free), **dangling pointers** (using memory after freeing), and **double free** (freeing the same memory twice). Master these, and you'll avoid the most common bugs in C/C++ programming. | Concept | What It Means | Why It Matters | |---------|--------------|----------------| | Stack memory | Auto-managed, fast, small | Local variables live here — cleaned up automatically | | Heap memory | Manual, large, flexible | Dynamic data lives here — YOU must free it | | `malloc` / `free` | C functions for heap allocation | The foundation of dynamic memory in C | | `calloc` / `realloc` | Allocate zeroed memory / resize | Extended C memory toolkit | | `new` / `delete` | C++ operators for heap allocation | Type-safe, calls constructors/destructors | | Memory leak | Allocated memory never freed | Program slowly eats RAM until it crashes |

5 topics3 videos3 quizzes
Week 4

Stack & Const

Alright, this week is a big one — we're tackling two topics that'll seriously level up your C++ game. First, you're going to build your very first **data structure** from scratch: the **stack**. What's a data structure? It's just a clever way of organizing data so that certain operations become really fast. And the stack is one of the simplest ones — it works on the **LIFO (Last In, First Out)** principle. Think of a stack of plates: the last plate you put on top is the first one you take off, right? You'll build a stack class using dynamic memory, so all that `new`/`delete` stuff from last week? You're about to put it to real use. Second, we're covering **const correctness** — this is a C++ superpower that lets you slap a "do not touch" sign on your data. The `const` keyword marks things as **read-only**, whether that's a variable, a function parameter, or even a whole method. And it's not just about being tidy — the compiler will actually catch bugs for you at compile time if you try to modify something you said was const. Pretty neat, right? | Concept | What It Means | Why It Matters | |---------|--------------|---------------| | Stack (LIFO) | Last In, First Out | Used in function calls, undo, parsing | | `const` variable | Value cannot change after initialization | Prevents accidental modification | | `const` reference | Cannot modify the referred-to variable | Avoids copies while protecting data | | `const` member function | Method promises not to modify the object | Enables calling on `const` objects | By the end of this week, you'll see how these two things fit together beautifully — building efficient data structures while keeping your code safe and easy to understand.

2 topics1 videos2 quizzes
Week 5

Classes & Objects

Okay, this week is a game-changer. Up until now, you've been writing what's called **procedural code** — basically a bunch of functions floating around, operating on separate chunks of data. It works, but it gets messy fast. What if you could bundle the data and the functions that work on that data into one neat package? That's **Object-Oriented Programming (OOP)**, and it's one of the most powerful ideas in all of programming. Here's the key concept: a **class** is like a blueprint. Think of yourself as an architect. You draw up plans for a house — how many rooms, where the doors go, how the plumbing works. That's your class. An **object** is an actual house built from those plans. You can build 10 houses from the same blueprint, each painted a different color and at a different address, but they all share the same structure. This week, we'll cover the building blocks of OOP: 1. **Member variables** (also called fields or attributes) — the data that lives inside each object 2. **Member functions** (also called methods) — the things an object can *do* 3. **Access specifiers** — `private` (only the class itself can touch it), `public` (anyone can use it), and `protected` (the class and its children can access it) 4. **Constructors** — special functions that set up an object the moment it's created 5. **Initializer lists** — the efficient C++ way to set member values during construction 6. **Encapsulation** — hiding the messy internals and only showing a clean interface to the outside world | Term | Meaning | Analogy | |------|---------|--------| | Class | Blueprint defining data + behavior | Architectural plan for a house | | Object | A specific instance of a class | An actual house built from the plan | | Member variable | Data stored in the object | Rooms, doors, windows in the house | | Member function | Operations the object can perform | Turning on lights, opening doors | | Constructor | Initializes the object when created | The construction crew that builds the house | | Encapsulation | Hiding internals, exposing public interface | The house hides its plumbing behind walls |

1 topics1 videos2 quizzes
Week 6

Header Files

Alright, let's be real — up until now, you've probably been putting all your code in one file. And that works fine when your program is small. But imagine scrolling through a 5,000-line file trying to find one function. Yeah, not fun. This week, you'll learn how the pros do it: by splitting code into **header files (`.h`)** and **source files (`.cpp`)**. And this isn't just about keeping things tidy — it's actually fundamental to how C++ compilation works, and it's what lets entire teams work on different parts of the same project without stepping on each other's toes. The idea is actually pretty simple: **header files contain declarations** — they tell the compiler what exists (class definitions, function prototypes). **Source files contain implementations** — the actual code that does the work. When another file needs to use your class, it just `#include`s the header to learn what's available, without needing to see how everything works under the hood. Think of it like this: the header is the table of contents of a book, and the source file is the actual chapters. We'll also cover **include guards** — this is a must-know. Without them, if two files both `#include` the same header, the compiler sees duplicate definitions and freaks out with errors. Include guards use `#ifndef`, `#define`, and `#endif` to make sure each header's contents only get included once, no matter how many files try to include it. | File Type | Extension | Contains | Purpose | |-----------|-----------|----------|---------| | Header file | `.h` or `.hpp` | Class declarations, function prototypes | Define the **interface** — what exists | | Source file | `.cpp` | Method definitions, function bodies | Provide the **implementation** — how it works | | Main file | `main.cpp` | `int main()` and program logic | **Entry point** — where execution begins | Once you get the hang of this, you'll never want to go back to single-file programs. This is how every real-world C++ project works, from small assignments to massive codebases with thousands of files.

1 topics1 videos1 quizzes
Week 7

Copy & Destructors

Alright, so let's say you've built a class that uses `new` to grab some memory from the heap. Everything works great... until you try to copy that object. And then your program crashes. But why? Well, here's the thing — when C++ copies an object for you by default, it just copies everything field by field. For simple stuff like `int` and `double`, that's totally fine. But for **pointers**? It copies the address, not the actual data. So now you've got two objects pointing to the **exact same chunk of memory**. When one gets destroyed and frees that memory, the other one is left holding a pointer to nothing. Boom — crash. This week, we're going to fix that. You'll learn the difference between a **shallow copy** (the dangerous default that just copies pointer addresses) and a **deep copy** (where you actually allocate fresh memory and duplicate the real data). And then we'll talk about the famous **Rule of Three** — basically, if your class needs a custom **destructor**, **copy constructor**, or **copy assignment operator**, it almost certainly needs all three. Think of it like this: if your class is responsible for cleaning up after itself, it also needs to know how to safely clone itself. By the end of this week, you'll be writing classes that manage dynamic memory like a pro — no memory leaks, no mysterious crashes.

2 topics1 videos2 quizzes
Week 8

Operator Overloading

You already know how to write `a + b` with integers, or `s1 == s2` with strings, or `cout << x` to print something, right? For built-in types, C++ already knows what all these operators mean. But what about YOUR custom classes? Like, what does it mean to "add" two `Vector2` objects together? Or to "print" a `Fraction`? The compiler has absolutely no idea — unless you tell it. And that's what **operator overloading** is all about. Here's the cool part: when you write `a + b`, the compiler is actually translating that into a function call behind the scenes — either `a.operator+(b)` (if it's a **member function**) or `operator+(a, b)` (if it's a **non-member/friend function**). So operator overloading is really just **syntactic sugar** — a fancy way to call a function that makes your classes feel as natural to use as `int` or `string`. This week you'll learn the two ways to overload operators: **member functions** (where the left operand is `this`, the object itself) and **friend functions** (where both operands are parameters, and the function gets access to private members). Some operators, like `<<` for printing, MUST be done as friend functions because the left operand is `ostream`, not your class. | Operator Category | Examples | Typical Implementation | |---|---|---| | Arithmetic | `+`, `-`, `*`, `/` | Member function: `T operator+(const T& other) const` | | Comparison | `==`, `!=`, `<`, `>` | Member function: `bool operator==(const T& other) const` | | Stream I/O | `<<`, `>>` | Friend function: `friend ostream& operator<<(ostream&, const T&)` | | Subscript | `[]` | Member function: `T& operator[](int index)` | | Assignment | `=` | Member function: `T& operator=(const T& other)` | A few operators **can't** be overloaded at all: the dot operator (`.`), scope resolution (`::`), the ternary operator (`?:`), and `sizeof`. But by the end of this week, you'll be making your custom classes feel just as natural to use as the built-in types.

1 topics1 videos2 quizzes
Week 9

Inheritance

Okay, let's talk about one of the biggest ideas in Object-Oriented Programming: **inheritance**. It's one of the four pillars of OOP (alongside encapsulation, polymorphism, and abstraction), and once you get it, a LOT of things in C++ will start to click. The basic idea is simple: you can create a new class (we call it a **derived class** or **child class**) that automatically gets all the stuff — variables, functions, everything — from an existing class (the **base class** or **parent class**). And then the new class can add its own stuff on top, or even **override** (replace) the inherited functions with its own versions. Think of it like biology: a `Dog` **is a** type of `Animal`, right? Every dog has all the properties of an animal (it breathes, it moves, it has a name) PLUS additional properties specific to dogs (it barks, it has a breed). In code, you'd write `class Dog : public Animal { ... };` — meaning Dog gets everything from Animal and can add its own features. This is what we call the **"is-a" relationship**: a `Dog` IS AN `Animal`, a `Circle` IS A `Shape`, a `Manager` IS AN `Employee`. Let's talk about a few key things you'll pick up this week. **Constructor chaining** — when you create a Dog object, the Animal constructor runs FIRST, then the Dog constructor. Makes sense, right? You have to build the foundation before you build the house on top of it. Then there's the **`protected`** access specifier — it sits between `public` and `private`. Protected members are accessible inside the class AND in derived classes, but not from outside code. And finally, the **`override`** keyword — it tells the compiler "hey, I'm intentionally replacing this function from the base class." If you accidentally make a typo in the function name, the compiler catches it for you. Pretty handy. | Access Specifier | Accessible in Class? | Accessible in Derived? | Accessible Outside? | |---|---|---|---| | `public` | Yes | Yes | Yes | | `protected` | Yes | Yes | No | | `private` | Yes | No | No | The beauty of inheritance is **code reuse** — you write the common functionality once in the base class, and every derived class automatically gets it for free. It also sets up a **type hierarchy** that makes polymorphism possible (that's next week's topic), where you can treat all sorts of different derived objects through a single base class interface.

1 topics1 videos2 quizzes
Week 10

Polymorphism

Okay, picture this: you've got an array of `Shape*` pointers, and each one is secretly pointing to a different shape — a `Circle`, a `Rectangle`, a `Triangle`. You loop through them and call `shape->area()` on every single one. Here's the cool part: the **right** version of `area()` runs for each shape, even though your pointer type is just `Shape*` for all of them. How does that work? Welcome to **polymorphism** — a Greek word that literally means "many forms." And honestly? It's probably the most powerful idea in all of object-oriented programming. But how does C++ actually figure out which `area()` to call at runtime? Think of it like this: imagine every class carries a little cheat sheet — a hidden lookup table that says "when someone calls `area()` on me, here's the actual function to run." That cheat sheet is called a **vtable** (virtual table), and the whole process of checking it at runtime is called **dynamic dispatch**. The keyword that kicks all of this off? `virtual`. Without it in your base class, C++ just blindly calls the base version. With `virtual`, it checks the actual object and picks the right function. Pretty neat, right? Now, what if the base class concept is too vague to even have a real implementation? Like, what's the area of a generic "shape"? That doesn't even make sense. So you mark the function as **pure virtual** with `= 0` (like `virtual double area() const = 0;`), and now the class becomes **abstract** — you literally cannot create objects of it. It's basically a contract that says "any class inheriting from me MUST fill in these blanks." Oh, and one more critical thing you need to know: **virtual destructors**. If you delete a derived object through a base pointer without one, only the base class destructor runs — meaning your derived class's cleanup code never executes, and you've got yourself a resource leak. | Concept | What It Means | Example | |---|---|---| | Virtual function | A function that uses dynamic dispatch to call the correct derived version at runtime | `virtual double area() const;` | | Pure virtual function | A function with no implementation in the base class — derived classes MUST override it | `virtual double area() const = 0;` | | Abstract class | A class with at least one pure virtual function — cannot be instantiated | `Shape` with `area() = 0` | | Dynamic dispatch | The runtime mechanism that looks up the vtable to call the correct function | `shape_ptr->area()` calls Circle's or Rect's version | | Virtual destructor | Ensures the derived class destructor runs when deleting through a base pointer | `virtual ~Shape() {}` | So why does all of this matter? Because polymorphism lets you write code that works with `Shape*` pointers, and it'll automatically handle **any** shape type — even ones that haven't been created yet. You're essentially coding against an interface, not a specific implementation, and that's a massive deal in real-world software.

1 topics1 videos2 quizzes
Week 11

Templates & Casts

This week we're tackling two things that professional C++ developers reach for all the time: **templates** and **type casts**. They sound intimidating, but let's break them down. Have you ever written a function that finds the max of two `int`s, then realized you need the exact same thing for `double`s, and then again for `string`s? That's annoying, right? You're copy-pasting the same logic over and over, just changing the type. **Templates** solve that problem. You write the function **once** — `template<typename T> T getMax(T a, T b)` — and the compiler automatically generates the right version for whatever type you throw at it. Think of it like a cookie cutter: you've got one shape (the template), but you can stamp out cookies from any dough (type). And here's the thing — you've been using templates this whole time! `vector<int>`, `vector<string>`, `vector<double>` are all generated from the same class template. Then there's **type casting**. In C, you'd just do `(int)x` and hope for the best. C++ says "nah, let's be more careful about this" and gives you four specific cast operators, each one built for a particular job: | Cast Operator | Purpose | Safety Level | Example | |---|---|---|---| | `static_cast<T>()` | Safe, well-defined conversions (numeric types, upcasting) | Safe (compile-time checked) | `double d = static_cast<double>(42);` | | `dynamic_cast<T*>()` | Downcasting polymorphic types (base ptr to derived ptr) | Safe (runtime checked, returns nullptr on failure) | `Circle* c = dynamic_cast<Circle*>(shapePtr);` | | `const_cast<T>()` | Add or remove `const` qualifier | Use with caution | `int* p = const_cast<int*>(constPtr);` | | `reinterpret_cast<T>()` | Bit-level reinterpretation between unrelated types | Dangerous (no checks) | Low-level/system programming only | By the end of this week, you'll know how to write generic functions and data structures that work with any type, and you'll know exactly which cast to reach for (and when to just not cast at all).

2 topics2 videos2 quizzes
Week 12

Final Project

Alright, this is the big one — the **capstone project**. Everything you've learned over the past 18 weeks? It all comes together right here. You're going to build a complete **Shape Management System** from scratch: a real C++ application that creates, stores, manipulates, and displays geometric shapes. And the cool part is that this one project touches basically **every major concept** from the entire course. Let me show you what I mean — check out how each thing you've learned maps directly to a piece of this project: | Course Concept | How It Appears in the Project | |---|---| | **Inheritance** | `Circle`, `Rectangle`, and `Triangle` all derive from the abstract `Shape` base class | | **Polymorphism** | A `Shape**` array holds different shape types; calling `area()` on each runs the correct derived version | | **Virtual Functions** | `area()`, `perimeter()`, `display()`, and `clone()` are all pure virtual in `Shape` | | **Dynamic Memory** | `ShapeCollection` manages a dynamic array of `Shape*` pointers allocated with `new` | | **Rule of Three** | `ShapeCollection` implements destructor, copy constructor, and copy assignment operator | | **Operator Overloading** | `==` compares shapes by area, `<` sorts by area, `<<` prints shape info, `[]` accesses by index | | **Const Correctness** | `const` on methods that do not modify state, `const&` parameters for efficiency | | **Static Members** | `Shape::totalShapes` tracks how many shapes exist across the entire program | | **Multi-file Organization** | Each class lives in its own `.h`/`.cpp` pair with include guards | | **The `clone()` Pattern** | Enables deep copying of derived objects through base class pointers | Don't let the size of this project intimidate you. The trick is to take it one step at a time — get one small piece working, test it, then move on to the next. And if you get stuck on something, flip back to the earlier weeks for a refresher. You've already learned all of this stuff individually; now you're just putting the puzzle pieces together.

2 topics0 videos1 quizzes

Overall Progress

Progress0%

Start your journey! Click on any week to begin learning C/C++.