6

An excerpt from Object-Oriented Programming with C++ by E Balagurusamy-

Using function pointers, we can allow a C++ program to select a function dynamically at run time. We can also pass a function as an argument to another function. Here, the function is passed as a pointer. The function pointer cannot be de-referenced. C++ also allows us to compare two function pointers.

Here it is written that function pointers cannot be dereferenced. But the following program ran successfully.

#include<iostream> 
int Multiply(int i, int j) {
    return i*j;
}  
int main() {
int (*p)(int , int);
p = &Multiply;
int c = p(4,5);
int d = (*p)(4,11);
std::cout<<c<<" "<<d;
return 0;
}

Here on the 4th last line, I have de-referenced the pointer. Is it correct? It was not giving any compiler time error, also what is written in the 4th last line is the same as what is written in the 5th last line? I have started learning C++ so please don't mind if I have asked something really stupid.

VIAGC
  • 639
  • 6
  • 14
  • 1
    Dereferencing function pointers using `*` is optional, the parens `()` imply that it's a function call. – πάντα ῥεῖ May 02 '21 at 09:34
  • They can be dereferenced, there are function references in addition to function pointers. Experiment: `int (&p)(int, int){Multiply};`. Must be an error or misunderstanding, always read the standard. – user1095108 May 02 '21 at 09:35
  • @user1095108 If I am getting it right `int (&p)(int, int){Multiply};` means that the address of function `p` and `Multiply` is same. – VIAGC May 02 '21 at 09:43
  • @ThunderKnight No, I just initialize a reference to a function, `p` is a reference. The same thing that dereferencing a function pointer produces. Hmmm, try `auto& p{Mupltiply}`. – user1095108 May 02 '21 at 10:17
  • @user1095108 Um I think that both `p` and `Multiply` have the same address, try `printf("address of function Multiply() and p() is :%p %p\n", Multiply, p);` – VIAGC May 02 '21 at 11:31
  • 1
    @ThunderKnight that's a different issue, address of a reference is the same as the object it refers to. What I wanted to convey was, that there exist pointers AND references to functions. A reference is what you get when you dereference a pointer. – user1095108 May 02 '21 at 20:17

1 Answers1

7

Your compiler is right, and the book is wrong.

But p(4,5) and (*p)(4,5) do the same thing, so it's almost never necessary to dereference function pointers.

[expr.unary.op]/1

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type ...

(bold mine)


please don't mind if I have asked something really stupid

No, good job on verifying what you read.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Ah got it now, when I de reference I get the function multiply and `p(4,5)` is same as that. Thanks, I would write to publishing company about this typo. – VIAGC May 02 '21 at 09:46