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.


bool MyClass::operator()()
class MyClass
virtual bool operator()();
11 Years
Discussion Span
Last Post by disc

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.

Edited by Nick Evan: n/a


found on google:

#include <iostream>
using namespace std;
class CVector {
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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.