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?
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;
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With