0

I was experimenting with new overloaded operators, I have created one void operator and another one that returns something when it's called:

#include <iostream>
struct chichachicha{
 int operator()(){
 return 25;
 };
};
struct boomboom{
 void operator()() {
 std::cout << "Hi folks!" << std::endl;
 };
};
int main(){
 chichachicha objC;
 int f = objC();
 std::cout << f << std::endl;
 boomboom objB;
 objB();
 return(0);
}

Is this the best way to write a code that does that?

How can I write an operator that can be called from anywhere in the code without instantiating the associated struct, that returns void/nothing and only prints a string of text? I'm not considering static methods, just operators.

gnat
20.5k29 gold badges117 silver badges308 bronze badges
asked Aug 16, 2012 at 3:31
2
  • 1
    The whole point of operator is to operate on something. If you don't want something, you don't want an operator. Probably a free function (the whole "everything should be in a class" mentality is alien to C++; things should be in namespaces). Commented Aug 16, 2012 at 8:33
  • The question sounds a bit like "I have a hammer, now how do I screw in this screw with it". Could you put in more detail about what you want to achieve without presuming that it should involve operator()? Commented Aug 16, 2012 at 8:35

1 Answer 1

4

Despite "I'm not considering static methods, just operators", the statement immediately before it suggests you are asking for a static operator(). If this were possible, the most vexing parse would be much more vexing!

Upon further inspection, it reads like you are basically in the market for a static function. The whole purpose of operator() is to make a functor. If you want a polymorphic version of operator(), I'm afraid you'll have to instantiate something somewhere.

answered Aug 16, 2012 at 4:37
3
  • i was experimenting with namespaces, but apparently i can't do more than what i can do in the main. Commented Aug 16, 2012 at 4:51
  • Why a static function? A simple free function would do that, too. Commented Aug 23, 2012 at 10:49
  • I use "static" and "free" interchangeably. Though static is often used to refer to an unbound function member of a class, the compiler treats them the same way. Commented Aug 23, 2012 at 14:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.