Search code examples
c++friend-functionlinker-errors

Interface with friend operator<<: why can't it link?


I have created a small interface for objects that can be represented in text mode using the operator<< like so:

// ICliObject.h

class ICliObject
{
public:

    ~ICliObject() = default;
    friend std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject);


protected:
    virtual void print(std::ostream& p_stream) const = 0;

};


std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)
{
    p_cliUiObject.print(p_stream);

    return p_stream;
}

When I inherit from this interface and try to build, the compilation works but I get the following linking error: In blablabla.cpp: multiple definition of operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)

In all derived classes, I have took care of not re-defining/declaring the operator. The only way I can solve my problem is in inlining the operator in ICliObject.h. What is going on?

Note: I use GCC on Ubuntu.


Solution

  • This has nothing to do with friend or with operator<< or with inheritance.

    Like any function (or object) defined at namespace scope, if you do so multiple times in your program (including by having it in a header file that you #include in multiple translation units), you will get this error.

    And, like in all those other cases, the solution is to either move the implementation to a "source file", or stick the inline keyword on it (which you already suggested, but it's literally the solution so I don't know why it's not acceptable).