Topic 14

Advanced C++ OOP Mechanics (Namespaces, Inline Functions, Memory Management, Exception Handling, Structure vs. Class)

3 min read3 questions to test yourself

1Definition

Advanced C++ OOP mechanics encompass specialized runtime and compile-time features including Namespaces (scope isolation), Inline Functions (macro-like optimization), Memory Management (delete vs delete[]), Exception Handling (try/catch), and structural nuances between Classes and Structures.

2Simple Explanation

  • Namespaces: Named postal zip codes. Two people can live at "100 Main Street", provided one lives in "Zip Code 90210" and the other in "Zip Code 10001".
  • Inline Functions: Copy-pasting text macros. Instead of jumping to a distant function in memory, the compiler pastes the code inline at the call site.
  • Memory Management: Returning leased equipment. Use delete for a single leased item and delete[] for an entire array of items.

3Real-Life Example / Analogy

  • Namespaces: Two students named "Alex" in a school are distinguished by their home surname or section (CS::Alex vs EE::Alex).
  • Exception Handling: An automobile emergency braking system. When an unexpected hazard occurs (throw), normal cruise control pauses and transfers handling to emergency brakes (catch).

4Diagram / Visual Representation

Namespace

Groups related names

Inline function

Suggests inline expansion

Memory management

Allocate / release resources

Exception handling

try / throw / catch

class vs struct

Different default member access

5Working / How It Works

  • delete vs delete[]: delete ptr; releases a single object pointer. delete[] arrPtr; reads array length headers, executes destructors for every array element, and frees the contiguous memory block.
  • Exception Handling: Code wrapped inside try {} throws an exception object via throw ExceptionObj;, halting current scope execution and transferring control to a matching catch(ExceptionObj &e) {} block.

6Types / Components / Characteristics

  • Summary Matrix:
Feature Key Syntax Primary Operational Purpose
Namespaces namespace ScopeName { ... } Eliminates identifier naming conflicts
Inline Functions inline void foo() { ... } Eliminates function call stack overhead
Single Delete delete ptr; Frees a single heap object instance
Array Delete delete[] arrPtr; Frees an array of heap objects and runs all destructors
Exception Handling try, catch, throw Robust runtime error recovery

7Solved Examples / Problems

Problem Statement: Write a C++ program demonstrating Namespaces, Inline Functions, Heap Array deletion (delete[]), and Exception Handling.

C++
#include <iostream>
#include <stdexcept>
using namespace std;
// User-defined Namespace
namespace CustomMath {
    inline int square(int x) { return x * x; } // Inline Function
}
int main() {
    // 1. Namespace & Inline usage
    cout << "Square: " << CustomMath::square(5) << endl;
    // 2. Exception Handling
    try {
        int denominator = 0;
        if (denominator == 0) {
            throw runtime_error("Division by Zero Error!");
        }
    } catch (const exception &e) {
        cout << "Caught Exception: " << e.what() << endl;
    }
    // 3. Array Heap Allocation & Deletion
    int* arr = new int[5];
    for(int i = 0; i < 5; i++) arr[i] = (i + 1) * 10;
    
    delete[] arr; // Deleting array correctly
    cout << "Heap Array Memory Successfully Freed." << endl;
    return 0;
}

Output:

Output
Square: 25
Caught Exception: Division by Zero Error!
Heap Array Memory Successfully Freed.

8Advantages, Disadvantages & Applications

  • Advantages:
    • Namespaces prevent collision issues in large enterprise multi-library software.
    • Exception handling separates normal business logic from error recovery logic.
  • Disadvantages:
    • Over-inlining functions inflates the compiled executable binary size (code bloat).
  • Applications: Enterprise C++ graphics engines, mission-critical flight controller software.

9Important Points to Remember

  • Always match new with delete, and new[] with delete[]. Mismatched deletion causes undefined heap corruption.
  • Inline declarations are suggestions to the compiler; the compiler may ignore inline hints for complex recursive functions.

10Test Your Understanding

  1. Conceptual Question: What is the danger of executing delete arr; instead of delete[] arr; on a dynamically allocated array of objects?
    Show answer
    delete arr; only executes the destructor for the first array element and frees memory incorrectly, causing resource leaks and heap corruption.
  2. MCQ: Which keyword is used to handle exceptions caught in a C++ try block?
    • A) except
    • B) catch
    • C) trap
    • D) finally
    Show answer
    B) catch
  3. Application Question: Write a custom namespace Physics containing a constant speedOfLight = 300000.
    Show answer
    namespace Physics { const int speedOfLight = 300000; }.

Finished this topic?

0 of 14 topics read in Object-Oriented Programming

Handwritten notes for the exam

Unit-wise SPPU notes and PYQs for this subject.

Helpful? Share it with your class

Free for everyone, no login needed.

Share topic