Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

() Operator overloading

Tags:

c++

c++11

This question has been asked before but not answered satisfactorily.

I have a class which is acting as an event handler and I would like to have a nice syntax for calling the event handler outside of an event. What this boils down to is overriding the () operator. I currently have

class EventHandler
{
public:
    void Call(void* sender, EventArgs e);

    void operator() (void* sender, EventArg e){ Call(sender, e); }
};

which works fine. I can call the event handler via

EventHandler EH;
EH(nullptr, EventArgs::Empty());

My problem lies in that I usually store the event handler on the heap so I need

EventHandler* EH;
EH(nullptr, EventArgs::Empty());  // error but this is the syntax I'm hoping for

but this can only be done with

EventHandler* EH;
(*EH)(nullptr, EventArgs::Empty());  // no error

How can I override the () operator to have it work with the pointer to the EventHandler object? I have seen some things that look like overloading the ->() operator instead of just the () operator but I haven't been able to make sense of it.

like image 969
Russell Trahan Avatar asked Mar 28 '26 21:03

Russell Trahan


1 Answers

The operator ->() doesn't exists.

There are two ways to call the operator.

EventHandler* EH;
(*EH)(nullptr, EventArgs::Empty());

or

EventHandler* EH;
EH->operator()(nullptr, EventArgs::Empty());

This works in the same way as the operator= or any other operator

like image 63
Vincent Avatar answered Apr 01 '26 08:04

Vincent