1
#include <iostream> 
using namespace std; 

int main() 
{ 
    char sample[] = "something really weird about c++"; 
    cout << sample << " - huh?"; 
    return 0; 
}

Here is simple c++ code that print something on screen, as I'm from python, it seems really weird for me that an object (according various sources 'cout' is object of class ostream) I just wonder how object can output something on screen or do something like statement and function without calling any method, my best guess << is overloaded under the hood and calls a method on it, 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 <<?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
ask455
  • 23
  • 6
  • 1
    Same as if you had typed: `cout.operator<<(sample).operator<<(" - huh?");` The `<<` is just syntactic sugar for a method call. – Eljay Nov 16 '20 at 17:20

1 Answers1

3

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185