0

I have a custom class that I am trying to print, I have it working how I am unsure why it is working and I was hoping someone could explain it. Taking the idea from this question I have created a small example,

class myclass { 

public:
    int i = 5;
};

and manages to print it by using,

std::ostream &operator<<(std::ostream &os, myclass const &m) { 
    return os << m.i;
}

myclass x;
std::cout << x;

However, other override operators have to include the class namespace such as,

myclass myclass::operator+(const myclass & c) {
    
    string temp;
    temp.i = i + c.i;
    return temp;
}

Notice here how I needed the namespace for the class myclass::operator+? Why was this not required to work for the << operator? How is it associated with myclass?

i.e I expected something like this,

                 v----this added
std::ostream myclass::operator<<(std::ostream &os, myclass const &m) { 
    return os << m.i;
}
J.Doe
  • 31
  • 4
  • 2
    That's not a namespace. That's just the class name. A typename is not a namespace. – Dai Jan 28 '21 at 22:56
  • 1
    `However, other override operators have to include the class namespace such as,` No they don't, they can be implemented as free functions as well. I.e. `myclass operator+(const myclass & a, const myclass & b)` – tkausl Jan 28 '21 at 22:57
  • Are you declaring the operator inside your class definition (in your `.h` header file) or only in your `.cpp` file? – Dai Jan 28 '21 at 22:59
  • Unrelated: `myclass::operator+` is weird looking. Allocates a `string`, operates on it, and then returns it, when it looks like the function should be returning a `myclass`. – user4581301 Jan 28 '21 at 22:59
  • Useful search term: ["Free function".](https://stackoverflow.com/questions/4861914/what-is-the-meaning-of-the-term-free-function-in-c) – user4581301 Jan 28 '21 at 23:01
  • 1
    Most `operator` overloads can be implemented as class methods, where `this` is handled as the left-hand operand. But `operator<<` and `operator>>` overloads can't be when dealing with `std::ostream`/`std::istream` I/O, as that would require those overloads to be added to the `std::ostream`/`std:istream` classes themselves, which is not allowed. Hence why custom `operator<<`/`operator>>` overloads in this situation are always implemented as non-member functions that take a `std::ostream`/`std::istream` as the 1st parameter. – Remy Lebeau Jan 28 '21 at 23:11

0 Answers0