The answer to this question seems to escape me, but how do you go about overloading with non-member functions. Do you just create a program level function and where ever the prototype (or definition) exists the operator is overloaded for that class type?
1 Answers
With a member function, this
would be the left hand side parameter, meaning your operator would only have one argument (or none for unary operators). With a freestanding function, you must supply either two or one arguments for binary or unary operators, respectively.
A good example is the <<
operator for streams:
class T;
// ...
std::ostream & operator<<(std::ostream &os, const T &val)
{
// ...
return os;
}
Here, os
is the left hand side parameter, and val
is the right hand side one.
As for "where", the operator must be defined where you use it. Generally, put them at the same place as the type you're overloading the operators for.
EDIT:
For non trivial operators (arithmetic operations on primitive types), operators are syntactic sugar for function calls. When you do this:
std::cout << "Hello";
It's like writing that:
operator<<(std::cout, "Hello");
But more readable.
For member operators, the left parameter will be this
(and that's why member operators have one less argument).

- 34,692
- 8
- 91
- 111
-
I'm guessing that std is a namespace not a class, so ostream is a freestadning function in the namespace std? So the difference between a memeber function and freestanding in this case is how it interacts with it's operands? – rubixibuc Apr 23 '11 at 05:46
-
No, the function's name is `operator<<`. `std::ostream &` is the return type. But ultimately the difference is that one is a method (and therefore has a `this` pointer) while the other isn't. – Etienne de Martel Apr 23 '11 at 05:47
-
I sry to ask, what does the std::ostream in this case represent, I know it's the return type, and std is a namespace but what is ostream? And where does it fit in with the namespace? – rubixibuc Apr 23 '11 at 05:50
-
`std::ostream` is the base class for all output streams. `std::cout` is a `std::ostream`. – Etienne de Martel Apr 23 '11 at 05:50
-
Wait is ostream a class defind in the std namespace? – rubixibuc Apr 23 '11 at 05:51