Also in Python you can overload operators. For example you can implement the special method __add__
and then call it via a + b
(see eg here for details). In principle the answer wouldn't be that different if your question was about Python instead of C++. Applying an operator is calling a function.
This
cout << sample;
is a short form of writing
cout.operator<<(sample);
ie it calls a method of cout
which is a std::ostream
.
You can provide an overload for the output operator for your custom type like this:
struct foo {};
std::ostream& operator<<(std::ostream& out, const foo& f) {
// do something with out and f
// expected is: write contents of f to out
// possible is: anything
return out;
}
Note that operators are not necessarily members. Some can only be implemented as member tough. More on operator overloading in C++: What are the basic rules and idioms for operator overloading?
For your specific request
if I'm right, would you like to make an object that that do something like 'cout' such as multiply some value [without calling a method or] by overloading <<?
struct multiplier {
int value = 1;
multiplier& operator<<(int x) {
value *= x;
return *this;
}
};
multiplier m;
m << 2 << 3 << 7;
std::cout << m.value; // prints 42
However, operator overloading should be used with caution and the principle of least surprise should be kept in mind. In the above example it would be much more natural to overload operator*=
instead, because thats the operator that is expected to multiply something on the given object.