1

Here's the code:

#include<iostream>
using namespace std;
typedef struct ptrs
{
    int (*addptr)(int a, int b);
}mems;

int add(int a, int b)
{
    int result = a+b;
    return result;
}

int main()
{
    mems ptrtest;
    ptrtest.addptr = &add;
    int c = (*ptrtest.addptr)(3,4);
    //int c = ptrtest.addptr(3,4);
    cout << c << endl;
    return 0;
}

if I replace the code int c = (*ptrtest.addptr)(3,4); with it's next line(annotated now), the result will be the same, why is that?

3 Answers 3

3

Of course, int c = (*ptrtest.addptr)(3,4); is the base case. However, in C++ (and in C as well), if you use the call (()) operator on a function pointer, it will do the "dereferencing" automatically. Just like when assigned to a variable of function pointer type, the name of a function decays into a function pointer, i. e.

int (*fptr)() = some_func;

is just as valid as

int (*fptr)() = &some_func;

albeit the type of func is int ()(void).

Sign up to request clarification or add additional context in comments.

3 Comments

Pedantically, ptrtest.addrptr(3,4) is the "base case"; C++ defines the function-call operator to act on function pointers, and it acts on functions via the standard function-to-pointer conversion.
@MikeSeymour That's interesting (as far as I know, in C, it works conversely, but I may need to read up on that). Do you have a section of the Standard to share?
Actually, I think I misread C++11 5.2.2/1 slightly. It's actually defined for both functions and pointers, and functions aren't converted to pointers. Sorry for the confusion.
1

Functions and function pointers can be used interchangeably, presumably for convenience. In particular, section 5.2.2 of the C++11 standard specifies that a function call can occur using a function or a pointer to a function.

Comments

0

C++ will automatically cast a function name to a function pointer (and vise versa) if doing so will create correct syntax.

1 Comment

This question is about the reverse of that.

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.