0

How to create a function pointer which takes a function pointer as an argument (c++)??? i have this code

    #include <iostream>
using namespace std;

int kvadrat (int a)
{
    return a*a;
}
int kub (int a)
{
    return a*a*a;
}
void centralna (int a, int (*pokfunk) (int))
{
    int rezultat=(*pokfunk) (a);
    cout<<rezultat<<endl;

}

void main ()
{
    int a;
    cout<<"unesite broj"<<endl;
    cin>>a;
    int (*pokfunk) (int) = 0;
    if (a<10)
        pokfunk=&kub;
    if (a>=10)
        pokfunk=&kvadrat;

    void (*cent) (int, int*)=&centralna; // here i have to create a pointer to the function "centralna" and call the function by its pointer

    system ("pause");
}
2
  • You might want to consider keeping your variable names in English. It will be easier for foreign (to you) programmers to understand your code. And I am not just talking about native English speaking programmers. Just a thought. Commented Jul 7, 2010 at 22:55
  • yeah i know, i had translated it but i pasted this code by accident, i've just noticed it. but the reply's helped alot Commented Jul 7, 2010 at 22:59

3 Answers 3

8

you will find it easier to typedef function pointers.

typedef int (*PokFunc)(int);
typedef void (*CentralnaFunc)(int, PokFunc);
...
CentralnaFunc cf = &centralna;
Sign up to request clarification or add additional context in comments.

4 Comments

this is very useful, but im not yet alowed to use it
You're forgetting "best" may be defined to include "complies to unspecified requirements".
@GMan: You've spent enough time on here to know what the purpose of the answer feature is, but thanks for your input.
Yes, it's the answer the questioner finds most helpful. And "helpful" may include anything the questioner wants, including compliance to certain specifications, made public or not. I agree typedef's are the best way to go (I always tell others to use more typedef's), but this answer is not helpful to the questioner. No biggie, you'll still get plenty of up-votes by people who agree with the answer, like me.
3

You need to use the function pointer type as the type of the parameter:

void (*cent) (int, int (*)(int)) = &centralna

Comments

2

void (*cent)(int,int (*) (int))=&centralna;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.