Question

In C++, I'm trying to write a function with function pointers. I want to be able to throw an exception if a function pointer is passed for a function that does not exist. I tried to handle the function pointer like a normal pointer and check if it is null

#include <cstddef>
#include <iostream>

using namespace std;

int add_1(const int& x) {
    return x + 1;
}

int foo(const int& x, int (*funcPtr)(const int& x)) {
    if (funcPtr != NULL) {
        return funcPtr(x);
    } else {
        throw "not a valid function pointer";
    }
}

int main(int argc, char** argv) {
try {
    int x = 5;

    cout << "add_1 result is " << add_1(x) << endl;

    cout << "foo add_1 result is " << foo(x, add_1) << endl;
    cout << "foo add_2 result is " << foo(x, add_2) << endl; //should produce an error
}
catch (const char* strException) {
    cerr << "Error: " << strException << endl;
}
catch (...) {
    cerr << "We caught an exception of an undetermined type" << endl;
}
    return 0;
}

but that doesn't seem to work. What is the best way to do this?

Was it helpful?

Solution

Checking for NULL is ok. But it is not possible to pass a pointer to a function that does not exist in the first place. So you don't have to worry about this. Although it is possible to just declare a function without defining it and pass the address of it. In that case you will get linker error.

OTHER TIPS

It will automatically throw an error if you are passing pointer which does not exist, if you are declaring a pointer then you have to initialize it with null to avoid garbage value, so comparing with null will not serve any purpose.

you still you want to check then try to assign some function(like add, sub etc.), if it takes then ok , if not then it will show again error as previously mentioned.

#include<cstddef>
#include <iostream>
using namespace std;

int foo(const int& x, int (*funcPtr)(const int& x)) {
    if (*funcPtr != NULL) {
        return funcPtr(x);
    }
    else
    {
        cout << "not a valid function pointer";
    }
}

If you want to 'throw' exception then you need to 'catch' it as well. Your code is failing because of two reasons in short, 1) You are not checking value of function pointer. 2) You are not properly catching the thrown exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top