Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with function pointers in C++

I'm planning on using function pointers to implement different functions in a class. However, I've run into a bit of trouble while trying to implement one such function.

The code is here:

std::vector<int> * (*create_vector)()
{
    std::vector<int> * vec_p = new std::vector<int>;
    return vec_p;
}

The errors are as follows:

3: [Error] expected primary-expression before '*' token
3: [Error] 'vec_p' was not declared in this scope
3: [Error] expected '}' before ';' token 
4: [Error] expected unqualified-id before 'return' 
5: [Error] expected declaration before '}' token

Is there something I'm misunderstanding about function pointers, or is it a different issue?

like image 631
Mloc Avatar asked Feb 08 '13 10:02

Mloc


3 Answers

std::vector<int> * (*create_vector)() declares a pointer to a function. A pointer. Not a function. You cannot go on with the pointer and pretend it's a function and define its body. You need to declare the two separately:

std::vector<int> * create_vector()
{
    std::vector<int> * vec_p = new std::vector<int>;
    return vec_p;
}

std::vector<int> * (*pcreate_vector)() = create_vector;
like image 69
Alexey Frunze Avatar answered Sep 28 '22 07:09

Alexey Frunze


You cannot declare a function and a function pointer at the same time.

Simply define your function:

std::vector<int>* create_vector()
{
    std::vector<int>* vec_p = new std::vector<int>;
    return vec_p;
}

Then, the best is to make a typedef (for code readability):

typedef std::vector<int>* (*create_vector_func)();

And now you can use it:

create_vector_func myFunc = &create_vector;
like image 24
Synxis Avatar answered Sep 28 '22 07:09

Synxis


Functions are implemented and function pointers can be pointed at functions. Function pointers themselves are not implemented.

Change to:

std::vector<int>* create_vector()
{
    std::vector<int> * vec_p = new std::vector<int>;
    return vec_p;
}

Then you can declare a function pointer to point at create_vector(). Managing function pointers can be simplified using a typedef:

typedef std::vector<int>* (*func_t)();    // C++03
typedef decltype(&create_vector) func_t; // C++11

func_t f = create_vector;
auto f = create_vector; // C++11 option also.

Avoid dynamic allocation if possible as it introduces additional complexity making the code more error prone. In C++11, move semantics were introduced so the cost of returning by value in this case are significantly reduced as the vector named vec_p will be moved from (as it is expiring), not copied from. If you must dynamically allocate use a form of smart pointer.

like image 29
hmjd Avatar answered Sep 28 '22 07:09

hmjd