C++ - must friend functions be defined in the header file?

Pacane picture Pacane · Dec 4, 2011 · Viewed 25.3k times · Source

I want to overload the operator << in one of my classes. The signature goes like this:

friend std::ostream& operator<<(std::ostream& os, const Annuaire& obj)

When I try to define it in the .cpp file it says that the operator<< exactly takes 1 argument, however, when I define it in the .h, it compiled/works fine.

This is how I define it in the .cpp file :

std::ostream& Annuaire::operator<<(std::ostream& os, const Annuaire& obj){ // ... }

Does it have anything to do with friend functions needing to be defined in header files?

Answer

Xeo picture Xeo · Dec 4, 2011

It can be defined in a cpp file, but it needs to at least be declared in a header file, otherwise all places where you want to use it will only see the stuff the stream itself gives you, not your overload.

// .h and in class
friend std::ostream& operator<<(std::ostream& os, MyClass const& v);

// .cpp
std::ostream& operator<<(std::ostream& os, MyClass const& v){
    // print it
}