0

In main.cpp:

#include <iostream>
#include "MyType.h"

int main(int argc, const char * argv[]) {
    MyType myobject = MyType();
    std::cout << myobject; //error here
    return 0;
}

in MyType.h:

#include <ostream>

class MyType {
public:
    MyType();
    std::ostream& operator<<(std::ostream &os);
};

in MyType.cpp:

#include "MyType.h"
#include <iostream>

MyType::MyType() {
}

std::ostream& MyType::operator<<(std::ostream &os){
    return os;
}

I am trying to overload << for a custom type. When I do, I get this error: /main.cpp:14:15: Invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'MyType')

What am I doing wrong here?

Drew
  • 12,578
  • 11
  • 58
  • 98

1 Answers1

7

You declare operator<< as a member function. So it only works if the invoking object is on its left hand side, as

MyType m;
m << (std::cout);

which looks like a monstrosity.

Best is to declare it as a friend,

friend std::ostream& operator<<(std::ostream &os, const MyType& rhs)
{
   os << ...; // do something with rhs here
   return os;
}

then you can "naturally" invoke it

std::cout << myobject;

which is translated as

operator<<(std::cout, myobject);

StackOverflow has a very nice guide about Operator overloading where you can find more details about operator overloading best practices.


Unrelated:

MyType myobject = MyType(); is redundant and inefficient, as you are copy constructing the left hand side from a temporary MyType() that has to be also constructed (although the compiler usually optimizes this via copy elision). It is enough and more efficient to just write MyType myobject.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252