Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function call via an object with public member pointer to function, without using dereference operator

Alright, I think the title is sufficiently descriptive (yet confusing, sorry).

I'm reading this library: Timer1.

In the header file there is a public member pointer to a function as follows:

class TimerOne
{
  public:
  void (*isrCallback)();  // C-style ptr to `void(void)` function
};

There exists an instantiated object of the TimerOne class, called "Timer1".

Timer1 calls the function as follows:

Timer1.isrCallback();

How is this correct? I am familiar with calling functions via function pointers by using the dereference operator.

Ex:

(*myFunc)();

So I would have expected the above call via the object to be something more like:

(*Timer1.isrCallback)();

So, what are the acceptable options for calling functions via function pointers, as both stand-alone function pointers and members of an object?

See also:

  1. [very useful!] Typedef function pointer?

Summary of the answer:

These are all valid and fine ways to call a function pointer:

myFuncPtr();
(*myFuncPtr)();
(**myFuncPtr)();
(***myFuncPtr)();
// etc.
(**********************************f)(); // also valid
like image 631
Gabriel Staples Avatar asked Dec 25 '22 16:12

Gabriel Staples


1 Answers

Things you can do with a function pointer.

1: The first is calling the function via explicit dereference:

int myfunc(int n)
{
}

int (*myfptr)(int) = myfunc; 

(*myfptr)(nValue); // call function myfunc(nValue) through myfptr.

2: The second way is via implicit dereference:

int myfunc(int n)
{
}

int (*myfptr)(int) = myfunc;

myfptr(nValue); // call function myfunc(nValue) through myfptr.

As you can see, the implicit dereference method looks just like a normal function call -- which is what you’d expect, since function are simply implicitly convertible to function pointers!!

In your code:

void foo()
{
    cout << "hi" << endl;
}

class TimerOne
{
public:

    void(*isrCallback)();
};


int main()
{

    TimerOne Timer1;
    Timer1.isrCallback = &foo;   //Assigning the address
    //Timer1.isrCallback = foo;   //We could use this statement as well, it simply proves function are simply implicitly convertible to function pointers. Just like arrays decay to pointer.
    Timer1.isrCallback();         //Implicit dereference
    (*Timer1.isrCallback)();      //Explicit dereference
        return 0;
}
like image 95
Nishant Avatar answered Jan 27 '23 01:01

Nishant