Hello,

Can anyone tell me what the code beneath means. I've searched but can't find a clear explanation. Maybe someone can give an example of how to use it.

Thanks...

bool MyClass::operator()()
{ 
 ....
}
class MyClass
{
virtual bool operator()();
}

Recommended Answers

All 6 Replies

You can use operator() to overload operators...
ok, say you've got a rectangle(height, witdh) and you want to add two:

Rectangle1 += Rectangle 2;

The compiler will be very sad.

If you make operator-overloading in your class, you can tell the compiler what it's suppose to do when you add two classes.
I don't have a concrete example, but google for operator-overloading.

found on google:

#include <iostream>
using namespace std;
 
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
 
CVector::CVector (int a, int b) {
x = a;
y = b;
}
 
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
 
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}

I already googled for operator overloading. Most of them I understand but not this specific one, operator().

operator() lets your values look like functions.

For example

struct greeter {
  std::string greeting_text;

  int operator()(const std::string& greetee) {
    std::cout << greeting_text << ", " << greetee << "!" << std::endl;
    return 12345;
  }
};

// later:
greeter alien_greet, programmer_greet;
alien_greet.greeting_text = "Greetings";
programmer_greet.greeting_text = "Hello";
int x;
x = alien_greet("earthling"); // prints "Greetings, earthling!"
programmer_greet("world"); // prints "Hello, world!"

std::cout << x << std::endl; // outputs 12345

Generally speaking, operator() tries to provide the ability to create functions that contain internal parameters of their own.

In addition, you may want to search for "functor" or "function object" for more information.

It makes more sense now. Thanks....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.