Function Pointers, Lambda Expressions, File IO, and Error Handling

0.0(0)
Studied by 0 people
call kaiCall Kai
Locked
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/33

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 8:40 PM on 7/26/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

34 Terms

1
New cards

What is a function pointer?

  • variable that stores the memory address of a function

  • allows a program to call a function indirectly

  • act as pointers to functions

2
New cards

What are the common uses of function pointers?

  • implementing callback functions where a function is executed in response to an event

  • providing custom comparison functions for algorithms such as sorting

  • creating tables of functions to dynamically select behaviour at runtime

3
New cards

What is the syntax for a function pointer?

Pointer to a function with no arguments:

return_type (*ptrName)();

Pointer to a function with arguments:

return_type (*ptrName)(type1, type2);

4
New cards

How do you create and call a simple function pointer?

void sayHello()
{
    std::cout << "Hello!";
}

void (*fp)() = sayHello;

fp();
  • fp stores the address of sayHello

  • fp() calls the function indirectly

5
New cards

What is an array of function pointers?

  • An array that stores multiple function addresses

  • Allows selecting different functions dynamically at runtime

int (*ops[3])(int, int) = {add, sub, mul};

6
New cards

What is a function callback?

when a function is executed in response to an event by passing a function pointer as an argument

void computeSum(int a, int b, void (*callback)(int))
{
    int sum = a + b;
    callback(sum);
}

Calling it:

ComputeSum(4, 7, onDone);

7
New cards

What is a functor (function object)?

  • An object that can be used like a function

  • Created by defining a class or struct that overloads the operator()

8
New cards

How do you create a functor?

class Square
{
public:
    int operator()(int num)
    {
        return num * num;
    }
};

Create and call:

Square s;
s(5);

9
New cards

What is the difference between a function pointer and a functor?

Function pointer:

  • Stores the address of an existing function

Functor:

  • Full object that can store data and behaviour together

  • Can maintain internal state between calls

10
New cards

When are functors used?

  • Providing custom operations to algorithms such as:

    • sorting

    • filtering

    • transforming data

  • When internal state or parameters are needed

11
New cards

How does a functor maintain internal state?

Because functors are objects, they can store data in member variables

class Counter
{
public:
    int count;

    Counter() : count(0) {}

    void operator()()
    {
        count++;
    }
};

count changes between calls

12
New cards

What is a lambda expression?

  • Anonymous function that can be defined directly inside the code

  • Allows programmers to write short, inline functions

  • Can capture variables from their surrounding scope

13
New cards

When are lambda expressions used?

  • When a small function is needed temporarily

14
New cards

What is the syntax of a lambda expression?

[capture] -> optional_return_type
{
    function body
}

15
New cards

What does the capture list do in a lambda?

  • Specifies which external variables are accessible inside the lambda

  • Examples:

    • [=] capture by value

    • [&] capture by reference

16
New cards

How is a lambda used with transform?

std::transform(numbers.begin(),
               numbers.end(),
               squares.begin(),
               [](double n)
               {
                   return n * n;
               });

The lambda calculates the square of each element

17
New cards

Why are files used in programs?

  • Data stored in RAM exists only while a program is running

  • Files allow programs to store information permanently on disk so it can be reused later

18
New cards

What is the fstream library?

The fstream library allows programs to:

  • open

  • read

  • write

  • close files stored on disk

19
New cards

What are the three main fstream classes?

  • ofstream → write to files

  • ifstream → read from files

  • fstream → read and write files

20
New cards

How do you write to a file?

std::ofstream outFile("output.txt");

outFile << id << std::endl;

outFile.close();

ofstream writes data to a file

21
New cards

How do you read from a file?

std::ifstream inFile("output.txt");

inFile >> id;

inFile.close();

ifstream reads data from a file

22
New cards

Why do we check if a file opened successfully?

To prevent errors when a file cannot be opened

if (!outFile)
{
    std::cout << "Error opening file.";
}

23
New cards

What is error handling?

Object-oriented programs separate the source of errors from their handling

It uses:

  1. try

  2. throw

  3. catch

24
New cards

What are the steps of exception handling?

  • A try statement is used

  • If an exception happens, throw an error

  • A catch statement handles the exception

25
New cards

What is the purpose of a try block?

Contains code that may cause an exception

try
{
    int result = safe_division(10,0);
}

26
New cards

What does throw do?

Throws an error when an exception happens

if (quotient == 0)
{
    throw "Division by 0 is undefined!";
}

27
New cards

What does catch do?

Handles the exception thrown by throw

catch (const char *error)
{
    std::cerr << error;
}

28
New cards

What are common uses of error handling?

  • Dynamic Memory Allocation

  • File stream I/O operations

  • Networking

  • Preventing out of bounds issues

29
New cards

How does division by zero error handling work?

int safe_division(int dividend, int quotient)
{
    if (quotient == 0)
    {
        throw "Division by 0 is undefined!";
    }

    return dividend / quotient;
}
  • Checks for invalid input

  • Throws an exception if quotient is zero

30
New cards

How do you handle file opening errors using exceptions?

std::ifstream inFile("output.txt");

if (!inFile)
{
    throw "Error: output.txt could not be opened.";
}

The catch block handles the error

31
New cards

What is the difference between function pointers, functors, and lambdas?

  • Function pointer: Stores the address of an existing function.

  • Functor: An object that behaves like a function and can store internal state.

  • Lambda: An anonymous inline function.

32
New cards

Which STL algorithms commonly use function pointers, functors, and lambdas?

  • sort

  • for_each

  • transform

33
New cards

Why are functors useful compared to normal functions?

Because functors can store internal state and parameters while also behaving like functions

34
New cards

Why are lambda expressions useful?

They make code more concise by allowing short, inline functions without creating separate functions