Search code examples
c++syntaxoperator-overloadingparentheses

Calling the parenthesis overload given a pointer


I can overload the parenthesis operator using the following signature:

char& operator()(const int r, const int c);

The intended usage of this would be:

// myObj is an object of type MyClass
myObj(2,3) = 'X'
char Y = myObj(2,3);

Which works as I expect. However, using the parenthesis operator when dealing with a pointer becomes convoluted. I would like to do:

// pMyObj is a pointer to an object of type MyClass
pMyObj->(2,3) = 'X';
char Y = pMyObj->(2,3);

However, such syntax yields the error Error: expected a member name (in VisualStudio at least).

The following does work but seems convoluted to me with a dereference and more parentheses than arguments.

char X = (*pMyObj)(2,3);

Is there a way to use the -> operator to call the () overload?


Solution

  • Yes there is, but you won't like it:

    pMyObj->operator()(2,3);