Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling overloaded operator () from object pointer

Tags:

c++

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); 
like image 248
Andry Avatar asked Jun 27 '12 07:06

Andry


People also ask

Can we overload this pointer?

There is no way to override operators on them. Pointers are (like char, int, float, etc...) a native type. You can create an object that behaves like a pointer and overload operators [->, *], but that will not overload [->, *] on the the native pointer.

Can we overload () operator in C++?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

How do you declare an overloaded operator?

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.

Can function call operator be overloaded?

The function call operator, when overloaded, does not modify how functions are called. Rather, it modifies how the operator is to be interpreted when applied to objects of a given type.


1 Answers

Not with that syntax, but you can do

 m->operator()(1,2); 
like image 193
Luchian Grigore Avatar answered Oct 16 '22 04:10

Luchian Grigore