954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

operator()

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()();
}
disc
Light Poster
29 posts since Sep 2006
Reputation Points: 10
Solved Threads: 1
 

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.

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

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;
}
Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

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

disc
Light Poster
29 posts since Sep 2006
Reputation Points: 10
Solved Threads: 1
 

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.

Rashakil Fol
Super Senior Demiposter
Team Colleague
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
 

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

GloriousEremite
Junior Poster in Training
65 posts since Jul 2006
Reputation Points: 108
Solved Threads: 14
 

It makes more sense now. Thanks....

disc
Light Poster
29 posts since Sep 2006
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You