C++ Programming Labs

Master exception handling, templates, and modern C++ smart pointers.

Exception Handling, Templates & Smart Pointers - Module 6

Write robust, generic, and memory-safe C++ code.

Lab 16: Exception Handling
Expert
Coding Challenge
Your Task: Learn to handle runtime errors gracefully using try-catch blocks. Exception handling prevents program crashes and allows recovery from errors.

Detailed Requirements:
1. Basic try-catch structure:
try { // Code that might throw throw runtime_error("Error!"); } catch (const exception& e) { cout << "Caught: " << e.what(); }
   • try - wrap risky code
   • throw - signal an error
   • catch - handle the error

2. Create a division function with error handling:
double divide(double a, double b) { if (b == 0) { throw invalid_argument("Division by zero!"); } return a / b; }

3. Catch specific exception types:
try { ... } catch (const invalid_argument& e) { ... } catch (const out_of_range& e) { ... } catch (const exception& e) { ... } // catches all

4. Common exception types:
runtime_error - general runtime errors
invalid_argument - bad function arguments
out_of_range - index out of bounds
logic_error - logical errors in code

Expected Output:
10 / 2 = 5 Error: Division by zero! Program continues normally...

Requirements Checklist

Include stdexcept header
Create a function that throws an exception
Use try block to wrap risky code
Use catch block with exception type
Call e.what() to get error message
Test both success and error cases
Output
// Click "Run Code" to compile and execute // Your program output will appear here
Hints & Tips
• Throw: throw runtime_error("message");
• Catch: catch (const exception& e) { e.what(); }
• Always catch by const reference
• More specific catches should come first
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 17: Function Templates
Expert
Coding Challenge
Your Task: Create generic functions using templates. Templates allow you to write code that works with any data type.

Detailed Requirements:
1. Create a template function:
template <typename T> T getMax(T a, T b) { return (a > b) ? a : b; }
   • template <typename T> declares a type parameter
   • T is a placeholder for any type
   • Compiler generates specific versions as needed

2. Use the template function:
int maxInt = getMax(5, 10); // T = int double maxDouble = getMax(3.14, 2.7); // T = double char maxChar = getMax('a', 'z'); // T = char

3. Template with multiple type parameters:
template <typename T, typename U> void printPair(T first, U second) { cout << first << ", " << second << endl; }

4. Create a template swap function:
template <typename T> void mySwap(T& a, T& b) { T temp = a; a = b; b = temp; }

Expected Output:
Max of 5 and 10: 10 Max of 3.14 and 2.7: 3.14 Before swap: a=5, b=10 After swap: a=10, b=5

Requirements Checklist

Create a template function with template<typename T>
Use the type parameter T in function
Call template with int arguments
Call template with double arguments
Create a template swap function
Test swap with reference parameters
Output
// Click "Run Code" to compile and execute // Your program output will appear here
Hints & Tips
• Declare: template <typename T>
• Use T as return type and parameter type
• For swap, use references: T& a, T& b
• Compiler deduces T from arguments
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 18: Smart Pointers
Expert
Coding Challenge
Your Task: Use modern C++ smart pointers for automatic memory management. Smart pointers prevent memory leaks by automatically freeing memory when no longer needed.

Detailed Requirements:
1. Include memory header:
#include <memory>

2. Use unique_ptr (exclusive ownership):
unique_ptr<int> ptr1 = make_unique<int>(42); cout << *ptr1 << endl; // Dereference like regular pointer // Memory freed automatically when ptr1 goes out of scope
   • Only ONE unique_ptr can own the object
   • Cannot be copied, only moved

3. Use shared_ptr (shared ownership):
shared_ptr<int> ptr2 = make_shared<int>(100); shared_ptr<int> ptr3 = ptr2; // Both point to same object cout << ptr2.use_count(); // Prints 2
   • Multiple shared_ptrs can share ownership
   • Memory freed when last owner is destroyed

4. Smart pointers with custom classes:
class Resource { public: Resource() { cout << "Created"; } ~Resource() { cout << "Destroyed"; } }; auto res = make_unique<Resource>();

Expected Output:
unique_ptr value: 42 shared_ptr value: 100 Reference count: 2 After copy, count: 2 Resource acquired Resource released

Requirements Checklist

Include memory header
Create unique_ptr using make_unique
Dereference unique_ptr to access value
Create shared_ptr using make_shared
Copy shared_ptr to demonstrate sharing
Use use_count() to check reference count
Output
// Click "Run Code" to compile and execute // Your program output will appear here
Hints & Tips
• unique_ptr: make_unique<Type>(value)
• shared_ptr: make_shared<Type>(value)
• Dereference: *ptr or ptr->
• Check count: ptr.use_count()
• Never use new/delete with smart pointers
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below