44

Consider the following:

class MyClass {
public:
   int operator ()(int a, int b);
};

When having:

MyClass* m = new MyClass();

I want to access the operator() method, so I could:

(*m)(1,2);

But can I do this?

m->(1,2);
Andry
  • 16,172
  • 27
  • 138
  • 246

2 Answers2

77

Not with that syntax, but you can do

 m->operator()(1,2);
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 3
    But note that if you find yourself needing to do this a lot, it may be easier and more readable to just define a normal member function. e.g. `m->do_it(1,2);` – David C. Apr 10 '18 at 21:00
  • Yeah I hate this syntax. @DavidC. you might not this option when working with 3rd party code. I prefer the syntax (*m)(1,3) -- either way it is ugly. – wcochran Jan 08 '23 at 18:53
8

If you won't change m (what it points to), you can substitute (*m) by a reference:

MyClass *m = new MyClass();
MyClass &r = *m;
r(1, 2);

See this answer for more details.

KinGamer
  • 491
  • 5
  • 7