Function pointers definitions possible?

Is it possible to have a pointer to function that has a definition, like the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

void Print();
void (*pt)();

int main()
{
	pt = Print;
	(*pt)();

	system("Pause");
 return 0;
}

void Print()
{
	cout << "Print Function" << endl;
}
void (*pt)()
{
   int total = 1 + 1
   cout << total << endl;
}


I tried running the following code myself, but was unsuccessful. I was wondering if there is another syntactical way of making a definition. Sorry if this is a stupid question.

Another question is should C++ programmers use function pointers? The only reason I ask is because most people on forums I go to usually disapprove of mixing C and C++ features together in one program. Why is that?
Thanks in advance.
closed account (28poGNh0)
Do you look for something like that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# include <iostream>
using namespace std;

int *function(void)
{
    int nbr = 45;
    int *ptr = &nbr;

    return ptr;
}

int main()
{
    int *ptr = function();

    cout << *ptr << endl;

    return 0;
}


Hope that helps
Is it possible to have a pointer to function that has a definition, like the following.


No, because a function pointer is not a function, it's a pointer.

In your example:

1
2
3
4
5
6
7
8
9
10
11
void Print();
void (*pt)();

int main()
{
	pt = Print;  // pt points to 'Print'
	(*pt)();  // calls whatever pt points to... so this calls 'Print'

	system("Pause");
	return 0;
}


pt isn't a function in of itself and therefore cannot have a body.


EDIT:

@Techno01: That is a function which returns a pointer, which is a very different thing than a function pointer.

It's also wrong because it's returning a pointer to a local var which will immediately go out of scope.



EDIT2:

Just saw the other question:

Another question is should C++ programmers use function pointers? The only reason I ask is because most people on forums I go to usually disapprove of mixing C and C++ features together in one program.


Function pointers are just as much a "C++ feature" as they are a "C feature", so yes it's OK to use them. Though many times you don't need to use them because abstract class interfaces provide similar functionality in an easier/safer manner.

C++11 even added a more robust 'function' object which can be used to hold function pointers. It makes them significantly easier to use, IMO.
Last edited on
Line 18-22 are not valid. You can't give a body to a function pointer.
Remove lines 18-22 and your program will work.

Thank you all for the replies. I understand things better now.

Last edited on
How do you declare a function pointer?

I was looking for a thing like this, and stumbled apon this thread. Thanks!
Topic archived. No new replies allowed.