Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
chessofnerd Avatar asked May 23 '13 20:05

chessofnerd


People also ask

Can pointer be overloaded?

Functions can be overloaded depending on whether the parameter type is an interior pointer or a native pointer.

What is pointer overloading?

Class Member Access Operator (->) Overloading in C++It is defined to give a class type a "pointer-like" behavior. The operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply.

Can [] operator be overloaded?

An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list. You must declare the overloaded = , [] , () , and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.


2 Answers

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

pMyObj->operator()(2,3);
like image 148
Luchian Grigore Avatar answered Oct 25 '22 20:10

Luchian Grigore


You could also create a reference to the pointed to object and do

MyObj& rMyObj = *pMyObj;
char Y = rMyObj(2, 3);

which might be a good alternative if your code will be read by people who could be confused by

pMyObj->operator()(2,3);
like image 20
Morten Fyhn Amundsen Avatar answered Oct 25 '22 19:10

Morten Fyhn Amundsen