Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can function pointers be de referenced

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.

like image 458
VyomYdv Avatar asked Mar 01 '23 15:03

VyomYdv


1 Answers

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.

like image 197
HolyBlackCat Avatar answered Mar 15 '23 14:03

HolyBlackCat